JavaScript Array.prototype.toSorted() Method
The toSorted() method returns a sorted copy of an array, leaving the original unchanged.
Description
The toSorted() method is the copying version of sort(). It returns a new sorted array and doesn't change the original, which makes it convenient where data should not be mutated, such as framework state. It sorts as strings by default, so pass a compare function for numbers.
The compare function works exactly as it does for sort(): return a negative number to put a first, a positive number to put b first, or zero to keep their order. The sort is stable, and undefined values are moved to the end.
Empty slots in sparse arrays become undefined in the result, so the new array is never sparse. The copy is shallow, so objects are shared with the original. Before toSorted() was added in 2023, the usual pattern was [...arr].sort(fn), which still works everywhere.
Syntax
array.toSorted()
array.toSorted(compareFn)Parameters
- compareFnOptional. A function that defines the sort order, as for
sort().
Return Value
A new, sorted array.
Example
Browser Support
The following information will show you the current browser support for the Array.prototype.toSorted() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





