JavaScript Array toSorted()Method

Array 对象参考手册JavaScript Array Object

Example

Sort array elements alphabetically:

//Sort const sites = ["Google", "Example", "JYSHARE", "Taobao"]; //Reverse the array const sites2 = sites.toSorted(); document.getElementById("demo").innerHTML = sites2;

Output:

Google,JYSHARE,Example,Taobao

Try it Yourself »

Definition and Usage

The toSorted() method is used to sort the elements of an array alphabetically.

The toSorted() method returns a new array.

The toSorted() method does not modify the original array.

toSorted() is the copying version of the sort() method.

Sort compare function:

  • String sorting (e.g., "Apple" before "Banana") usually works in alphabetical order.
  • Numeric sorting may produce incorrect results, because string comparison treats "25" as greater than "100" (because "2" is greater than "1").
  • This can be solved by providing a "compare function" (see examples below).

Browser Support

toSorted() is an ES2023 feature.

As of July 2023, all modern browsers support this feature:

Chrome 110 Edge 110 Firefox 115 Safari 16.4 Opera 96
Feb 2023 Feb 2023 Jul 2023 Mar 2023 May 2023

Syntax

array.toSorted(compareFunction)

Parameters

Parameter Description
compareFunction (optional)

A function that defines the sort order. The function should return a negative, zero, or positive value depending on the arguments, for example:

function(a, b) { return a - b; }

When sort() compares two values, it passes the values to the compare function, and sorts the values according to the returned value (negative, zero, or positive).

Return Value

Type Description
Array Returns a new sorted array.

More Examples

Sort in descending order:

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const fruits2 = fruits.toSorted();
fruits2.reverse();

Find the minimum value:

Example

const points = [40, 100, 1, 5, 25, 10];
let points2 = points.toSorted(function(a, b) { return a - b; });
let lowest = points2[0];

Find the maximum value:

Example

const points = [40, 100, 1, 5, 25, 10];
let points2 = points.toSorted(function(a, b) { return b - a; });
let highest = points2[0];

Another method to find the maximum value:

Example


const points = [40, 100, 1, 5, 25, 10];
let points2 = points.toSorted(function(a, b) { return a - b; });
let highest = points2[points.length - 1];

Array 对象参考手册JavaScript Array Object

Other Extensions