JavaScript (ES2026) reference · Array Methods
JavaScript Array toSorted() Method
Return a new sorted array, leaving the original unchanged. Takes the same compare function as sort().
JavaScript (ES2026) Since ES2023
Syntax
array.toSorted(compareFn)
Parameters
| Parameter | Description |
|---|---|
compareFn optional |
As in sort(). |
Return value
A new array.
Examples
const prices = [30, 5, 12];
console.log(prices.toSorted((a, b) => a - b), prices);
Output
[ 5, 12, 30 ] [ 30, 5, 12 ]
const names = ["bob", "Alice", "carol"];
console.log(names.toSorted((a, b) => a.localeCompare(b)));
Output
[ 'Alice', 'bob', 'carol' ]
Version history
| Version | Change |
|---|---|
| JavaScript ES2023 | Added |
In other languages
sorted()· Python
Related
array.sort()· Sort the array in place and return it. Without a compare function elements are sorted as strings, so numbers need one.array.toReversed()· Return a new array with the elements in reverse order, leaving the original unchanged.array.toSpliced()· Return a new array with elements removed, replaced or inserted at a position, leaving the original unchanged.- JavaScript Arrays · tutorial
- JavaScript Array Methods · tutorial