Sub topic 3
Sorting Without Mutation: toSorted and Copies
This chapter assumes you know how comparator functions work, and that you understand the difference between changing an existing value and creating a new one. It covers one practical question. When you sort, do you want the original array to change?
sort() Changes the Array You Give It
Array.prototype.sort sorts in place. It rearranges the elements of the array you call it on, then returns that same array. The return value is not a copy. It is the same object.
const scores = [50, 90, 70, 80];
const result = scores.sort((a, b) => b - a);
console.log(result); // [90, 80, 70, 50]
console.log(scores); // [90, 80, 70, 50]
console.log(result === scores); // trueBecause the result is returned, it is easy to assume sort produces a new array. That assumption causes quiet bugs, usually inside helper functions:
function topThree(list) {
return list.sort((a, b) => b - a).slice(0, 3);
}
const scores = [50, 90, 70, 80];
console.log(topThree(scores)); // [90, 80, 70]
console.log(scores); // [90, 80, 70, 50] <- caller's data changedThe caller asked a question and got its data rearranged as a side effect. If another part of the program relied on the original order, such as insertion order or the order rows arrived from a server, that order is now lost.
toSorted(): A Sorted Copy
ES2023 added toSorted. It takes the same optional comparator as sort, but it returns a new array and leaves the original untouched.
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
console.log(original); // [3, 1, 2]
console.log(sorted); // [1, 2, 3]
console.log(sorted === original); // falseWithout a comparator, toSorted() uses the same string-based default ordering as sort(). The only difference is whether the input changes.
Copy-Then-Sort for Older Environments
toSorted ships in Node.js 20+, Chrome 110+, Firefox 115+, and Safari 16+. If you need to support older runtimes without a polyfill, copy the array first and sort the copy:
const original = [3, 1, 2];
const viaSpread = [...original].sort((a, b) => a - b);
const viaSlice = original.slice().sort((a, b) => a - b);
console.log(original); // [3, 1, 2]
console.log(viaSpread); // [1, 2, 3]
console.log(viaSlice); // [1, 2, 3]Both forms give the same result in normal use. toSorted says what you mean in one call, so prefer it when your targets support it.
The Copy Is Shallow
toSorted and the copy idioms create a new array, but they do not copy the elements inside it. With objects, both arrays point to the same objects.
const users = [
{ name: 'Bo', age: 25 },
{ name: 'Ana', age: 30 }
];
const byAge = users.toSorted((a, b) => a.age - b.age);
byAge[0].age = 99;
console.log(users[0].age); // 99
console.log(byAge[0] === users[0]); // trueThe order of users is protected. The objects are not. If you need independent objects, map them to new ones (users.map(u => ({ ...u }))) or use structuredClone before changing them.
Holes in Sparse Arrays
A sparse array has empty slots, called holes. The two methods treat holes differently. sort keeps holes as holes and moves them to the end. toSorted turns them into real undefined values.
console.log([3, , 1].sort()); // [1, 3, <1 empty item>]
console.log([3, , 1].toSorted()); // [1, 3, undefined]This rarely matters in practice, but it can surprise you if your later code checks i in arr.
The Change-by-Copy Family
toSorted came in the same release as three other non-mutating methods. Each one mirrors a method that mutates:
| Mutating | Non-mutating (ES2023) | Returns |
|---|---|---|
| `sort(fn)` | `toSorted(fn)` | sorted copy |
| `reverse()` | `toReversed()` | reversed copy |
| `splice(i, n, ...items)` | `toSpliced(i, n, ...items)` | copy with edits (not the removed items) |
| `arr[i] = v` | `with(i, v)` | copy with one element replaced |
const nums = [5, 2, 8];
const descending = nums.toSorted((a, b) => a - b).toReversed();
console.log(descending); // [8, 5, 2]
console.log(nums); // [5, 2, 8]Choosing Between Them
- Use
sortwhen you own the array, nobody else holds a reference to it, and avoiding an extra allocation matters, for example a large temporary array built inside one function. - Use
toSortedfor function arguments, shared or frozen data, and framework state, where a new reference is how change detection works. - Use
[...arr].sort(fn)when you need non-mutating behavior on runtimes withouttoSorted.
Exercise
A React component holds const [items, setItems] = useState([...]). A handler runs setItems(items.sort((a, b) => a.price - b.price)), but the list sometimes fails to re-render. Why, and what is the fix?
Show answer
sort() mutates items in place and returns the same array reference. React compares the old and new state by reference, sees the same object, and may skip the re-render. The handler has also mutated state directly. The fix is to pass a new array: setItems(items.toSorted((a, b) => a.price - b.price)), or [...items].sort(...) on older runtimes.
Exercise
After const copy = people.toSorted((a, b) => a.name.localeCompare(b.name)); copy[0].name = 'Zed';, does people change? Explain.
Show answer
The order of people stays the same, but one of its objects changes. toSorted makes a shallow copy, so copy[0] is the same object as one of the elements of people. Renaming it through copy also renames it in people.