JavaScript Array toSorted() Method
Example
Sorts the elements of an array in alphabetical order:
//
Sorting
const
sites
=
[
"
"
,
"
Runoob
"
,
"
JYSHARE
"
,
"
Taobao
"
]
;
//
Reverse the array
const
sites2
=
sites
.
toSorted
(
)
;
document
.
getElementById
(
"
demo
"
)
.
innerHTML
=
sites2
;
Output result:
Google,JYSHARE,Runoob,Taobao
Try it »
Definition and Usage
The toSorted() method is used to sort the elements of an array in alphabetical order.
The toSorted() method returns a new array.
The toSorted() method does not modify the original array.
toSorted() is a copy version of the sort() method.
** Sort comparison function: **
- String sorting (e.g., "Apple" before "Banana") usually works alphabetically.
- Numeric sorting may produce incorrect results, because string comparison treats "25" as greater than "100" (since "2" is greater than "1").
- This can be resolved by providing a "comparison function" (see the example below).
Browser support
toSorted() is a feature of ES2023.
Since 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
| Parameters | Description |
|---|---|
| compareFunction (optional) |
A function that defines the sort order. It should return a negative, zero, or positive value based on the arguments, for example: |
| function(a, b) { return a - b; }
When sort() compares two values, it passes them to the comparison function and sorts them based on the return 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 way 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
]
;
JavaScript Array object