The JavaScript array.toSorted() method
The toSorted() method returns a new sorted array, leaving the original untouched: the non-mutating version of sort(). [3, 1, 2].toSorted() returns [1, 2, 3] without changing the source. Like sort(), it sorts as strings by default, so pass a compare function for numbers.
Overview
toSorted() does exactly what sort() does, with one crucial difference: it returns a new sorted array instead of mutating the original. That solves the most common sort() footgun: accidentally reordering an array other code still depends on. Before toSorted(), you had to copy first ([...arr].sort()); now it's built in.
It takes the same optional compare function, with the same rules: by default it sorts elements as strings, so [10, 2, 1].toSorted() gives the surprising [1, 10, 2]. For numbers, pass (a, b) => a - b for ascending or b - a for descending, identical to sort().
It's one of a set of non-mutating array methods added recently (alongside toReversed(), toSpliced() and with()) that return copies instead of changing the array in place. These are ideal for immutable patterns like React state. Browser support is now solid across all current browsers; for older environments the copy-then-sort idiom still works.
Syntax
const sorted = array.toSorted()
const sorted = array.toSorted(compareFn)
[3, 1, 2].toSorted() // [1, 2, 3], original unchanged
[10, 2, 1].toSorted((a, b) => a - b) // [1, 2, 10]
Parameters
The array.toSorted() method accepts the following parameters.
| Parameter | Description |
|---|---|
compareFn |
Optional. Function comparing two elements (a, b): negative to put a first, positive to put b first. Omit it and elements sort as strings. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const scores = [42, 8, 100, 16];
const sorted = scores.toSorted((a, b) => a - b);
document.getElementById('out').textContent =
'sorted: ' + sorted.join(', ') + '\n' +
'original: ' + scores.join(', '); // original unchanged
</script>
Best practices
- Use
toSorted()when you need a sorted copy and must keep the original order. - Pass a compare function for numbers (
(a, b) => a - b), or the default string sort mis-orders them. - Prefer it over
[...arr].sort()in modern code; it states the non-mutating intent. - Use the mutating sort() only when changing the array in place is what you want.
Frequently asked questions
What is the difference between toSorted() and sort()?
toSorted() returns a new sorted array and leaves the original alone; sort() sorts the array in place (mutating it).Does toSorted() sort numbers correctly?
arr.toSorted((a, b) => a - b) for numbers.Is toSorted() supported in all browsers?
[...arr].sort() instead.