Sub topic 4
Sorting without mutation with toSorted
This chapter assumes you know how JavaScript arrays and indexing work, how Array.prototype.sort behaves, how to write arrow functions, and how primitive values differ from object references.
The problem with sort
sort reorders the array you call it on. It also returns that same array, which hides the mutation. Code like the following looks as if it makes a sorted copy, but it does not:
const original = [3, 1, 2];
const sorted = original.sort((a, b) => a - b);
console.log(sorted); // [1, 2, 3]
console.log(original); // [1, 2, 3] (changed too)
console.log(sorted === original); // trueAny other code that holds a reference to original now sees the new order. Before ES2023 the usual fix was to copy the array first with [...arr].sort() or arr.slice().sort(). toSorted makes that copy for you.
How toSorted works
toSorted takes the same optional comparator as sort. It returns a new array with the elements in sorted order and leaves the original untouched.
const scores = [40, 100, 1, 5];
const mutated = [...scores];
mutated.sort();
console.log(mutated); // [1, 100, 40, 5] (string order)
const sorted = scores.toSorted((a, b) => a - b);
console.log(sorted); // [1, 5, 40, 100]
console.log(scores); // [40, 100, 1, 5] (unchanged)When you call it without a comparator, toSorted compares elements as strings, exactly like sort. That is why 100 comes before 40 in the default order. The copying behavior changes nothing about ordering rules, so numbers still need a comparator.
Sorting objects by a key
In real code you usually sort records. The comparator reads a property from each element:
const products = [
{ name: "Lamp", price: 30 },
{ name: "Desk", price: 120 },
{ name: "Chair", price: 45 }
];
const cheapestFirst = products.toSorted((a, b) => a.price - b.price);
const priciestFirst = products.toSorted((a, b) => b.price - a.price);
const byName = products.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(cheapestFirst.map(p => p.name)); // ["Lamp", "Chair", "Desk"]
console.log(priciestFirst.map(p => p.name)); // ["Desk", "Chair", "Lamp"]
console.log(byName.map(p => p.name)); // ["Chair", "Desk", "Lamp"]
console.log(products.map(p => p.name)); // ["Lamp", "Desk", "Chair"]You can derive several orderings from one source array, and none of them affects the others. This is a common need for tables with sortable columns, where the source data has to stay in its original order.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `arr.sort()` when you meant a copy | The original is reordered | Use `arr.toSorted()` |
| Calling `toSorted()` on numbers with no comparator | String order, so `[1, 100, 40, 5]` | Pass `(a, b) => a - b` |
| Expecting `toSorted` to sort in place | The return value is discarded and the array looks unsorted | Assign the result: `const s = arr.toSorted(...)` |
| Passing a non-function, such as `toSorted("asc")` | Throws a `TypeError` | Pass a function or nothing |
Exercise
Given const ages = [30, 9, 21];, what do ages.toSorted() and ages contain afterward, and how would you get ascending numeric order?
Show answer
ages.toSorted() returns [21, 30, 9] because the default comparison is by string ("21" < "30" < "9"). ages remains [30, 9, 21]. Use ages.toSorted((a, b) => a - b) to get [9, 21, 30].
Exercise
A teammate writes const top = users.sort((a, b) => b.score - a.score).slice(0, 3); in a render function. What bug does this cause, and what is the one-word fix?
Show answer
sort reorders users in place on every render, so other code that reads users sees the changed order. Replace sort with toSorted so a new array is sorted and users stays as it was.