The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order.
The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order.
toSorted() toSorted(compareFn)
A new array with the elements sorted in ascending order.
See sort() for more information on the compareFn parameter.
When used on sparse arrays, the toSorted() method iterates empty slots as if they have the value undefined.
The toSorted() method is generic. It only expects the this value to have a length property and integer-keyed properties.
const months = ["Mar", "Jan", "Feb", "Dec"]; const sortedMonths = months.toSorted(); console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar'] console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec'] const values = [1, 10, 21, 2]; const sortedValues = values.toSorted((a, b) => a - b); console.log(sortedValues); // [1, 2, 10, 21] console.log(values); // [1, 10, 21, 2]
For more usage examples, see sort().
Empty slots are sorted as if they have the value undefined. They are always sorted to the end of the array and compareFn is not called for them.
console.log(["a", "c", , "b"].toSorted()); // ['a', 'b', 'c', undefined] console.log([, undefined, "a", "b"].toSorted()); // ["a", "b", undefined, undefined]
The toSorted() method reads the length property of this. It then collects all existing integer-keyed properties in the range of 0 to length - 1, sorts them, and writes them into a new array.
const arrayLike = { length: 3, unrelated: "foo", 0: 5, 2: 4, 3: 3, // ignored by toSorted() since length is 3 }; console.log(Array.prototype.toSorted.call(arrayLike)); // [4, 5, undefined]
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
toSorted |
110 | 110 | 115 | 96 | 16 | 110 | 115 | 74 | 16 | 21.0 | 110 | 1.31 | 20.0.0 | |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted