Sub topic 4
Sorting without mutation with toSorted
This chapter assumes you know how JavaScript arrays and indexing work and how Array.prototype.sort behaves, including its comparator argument. It also assumes you can read arrow functions and know that objects are passed by reference. The earlier chapter on comparators explained why the default sort order is based on strings. Here the focus is on toSorted itself: what it returns, what it leaves alone, and where it behaves differently from sort.
The working model
toSorted is the copying version of sort. It takes the same optional comparator and orders the elements by the same rules. It also uses the same stable algorithm. The difference is where the result goes:
| Method | Changes the receiver? | Returns |
|---|---|---|
| `arr.sort(compare)` | Yes, reorders `arr` in place | The same array object, `arr` |
| `arr.toSorted(compare)` | No | A new array with the sorted elements |
The basic case looks like this:
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)The first half copies the array by hand before calling sort, which was the usual pattern before ES2023. The second half does the same work in one call and never touches scores.
The return-value trap that toSorted removes
sort returns its receiver, and a lot of bugs come from that. Code like const sorted = arr.sort() reads as if it makes a sorted copy. It actually gives you a second name for the same array, which has now been reordered.
const original = [3, 1, 2];
const alias = original.sort((a, b) => a - b);
console.log(alias === original); // true
console.log(original); // [1, 2, 3] (mutated)
const fresh = [3, 1, 2];
const copy = fresh.toSorted((a, b) => a - b);
console.log(copy === fresh); // false
console.log(fresh); // [3, 1, 2]The bug gets worse when the array comes from somewhere else: a function parameter, a module-level constant, a cached API response, or a component's props. A helper like the one below changes its caller's data without saying so:
function topThreeBad(list) {
return list.sort((a, b) => b - a).slice(0, 3);
}
function topThree(list) {
return list.toSorted((a, b) => b - a).slice(0, 3);
}
const readings = [12, 90, 45, 7, 63];
console.log(topThree(readings)); // [90, 63, 45]
console.log(readings); // [12, 90, 45, 7, 63]
console.log(topThreeBad(readings)); // [90, 63, 45]
console.log(readings); // [90, 63, 45, 12, 7] (caller's array changed)Both functions return the same value. Only topThree leaves readings alone. Code that reads readings later would see a different order after a call to topThreeBad, and nothing at the call site would tell you why.
Sorting records with comparators
toSorted accepts any comparator that sort accepts. The comparator is called with two elements and returns a negative number, zero, or a positive number. These patterns cover most real data:
const products = [
{ name: "Lamp", price: 30, category: "home" },
{ name: "Desk", price: 120, category: "office" },
{ name: "chair", price: 85, category: "office" },
{ name: "Rug", price: 30, category: "home" }
];
// Numeric, descending
const byPriceDesc = products.toSorted((a, b) => b.price - a.price);
console.log(byPriceDesc.map(p => p.name)); // ["Desk", "chair", "Lamp", "Rug"]
// Strings, locale-aware and case-insensitive
const collator = new Intl.Collator("en", { sensitivity: "base" });
const byName = products.toSorted((a, b) => collator.compare(a.name, b.name));
console.log(byName.map(p => p.name)); // ["chair", "Desk", "Lamp", "Rug"]
// Two keys: category ascending, then price ascending
const byCategoryThenPrice = products.toSorted(
(a, b) => a.category.localeCompare(b.category) || a.price - b.price
);
console.log(byCategoryThenPrice.map(p => p.name)); // ["Lamp", "Rug", "chair", "Desk"]
console.log(products.map(p => p.name)); // ["Lamp", "Desk", "chair", "Rug"] (unchanged)The two-key comparator works because || falls through to the second comparison only when the first one returns 0. If Intl.Collator is new to you: building one collator and reusing it is faster than calling localeCompare with options on every comparison, because the collator object holds the locale setup.
Stability
Like sort, toSorted is stable. Elements that compare equal keep their original relative order. That lets you sort by one key and know that ties keep the order they came in:
const tasks = [
{ title: "b", priority: 2 },
{ title: "a", priority: 1 },
{ title: "c", priority: 2 },
{ title: "d", priority: 1 }
];
const byPriority = tasks.toSorted((x, y) => x.priority - y.priority);
console.log(byPriority.map(t => t.title)); // ["a", "d", "b", "c"]Within priority 1, a comes before d because it came first in tasks. The same is true for b and c within priority 2.
Edge cases and common errors
Frozen and read-only arrays
sort writes back into its receiver, so it fails on a frozen array. toSorted only reads the receiver, so it works:
const frozen = Object.freeze([3, 1, 2]);
try {
frozen.sort();
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(frozen.toSorted()); // [1, 2, 3]
console.log(Object.isFrozen(frozen.toSorted())); // falseThe returned array is a normal, unfrozen array. If you need it frozen, freeze it yourself. Frozen arrays show up in configuration objects and state libraries that freeze in development builds, and in code that uses Object.freeze to enforce immutability. toSorted is the method that works with all of them.
An invalid comparator throws before any work happens
The comparator must be either undefined or a function. Anything else throws a TypeError right away, before any copying:
const nums = [2, 1];
console.log(nums.toSorted(undefined)); // [1, 2]
try {
nums.toSorted(null);
} catch (err) {
console.log(err instanceof TypeError); // true
}People hit this when they forward an optional argument and default it to null. Default it to undefined instead, or leave the parameter out.
A comparator that returns booleans
(a, b) => a > b returns true or false. These become 1 or 0, and the method never sees a negative result. With toSorted, the original array is not damaged by this, but the result may be in the wrong order, and the order can change between engines. Return a signed number every time. The comparators chapter covers this in detail.
Undefined values
undefined elements are never passed to the comparator. They always go to the end of the result, whatever the comparator does. This matches sort. The later chapter on sparse arrays shows how holes are read as undefined and end up in the same place.
const withGaps = [3, undefined, 1];
console.log(withGaps.toSorted((a, b) => b - a)); // [3, 1, undefined]Shallow results
toSorted copies the array, not its elements. When the array holds objects, the new array points to the same objects. Changing byPriority[0].title would also change the matching object in tasks. The shallow-copies chapter covers what stays shared and how to deal with it.
When to choose toSorted, and when not to
toSorted allocates a new array of the same length on every call. In most application code, that cost is small compared to the bugs it prevents. A few cases call for a closer look:
| Situation | Prefer |
|---|---|
| Sorting data you received as a parameter, prop, or shared state | `toSorted` |
| Deriving a sorted view for display while keeping the source order | `toSorted` |
| Sorting a frozen or read-only array | `toSorted` |
| A large array you just built locally, which nothing else references | `sort` is fine and avoids a second allocation |
| A hot loop that repeatedly sorts a big buffer you own | `sort`, to avoid allocation pressure |
| A runtime without ES2023 support | A fallback, covered in the runtime-support chapter |
For local arrays, arr.toSorted(cmp) and [...arr].sort(cmp) produce the same result. toSorted states the intent more clearly, makes one copy instead of a spread followed by a sort, and also works on array-like objects through Array.prototype.toSorted.call, which a later chapter covers.
Exercise
A teammate writes const ranked = leaderboard.sort((a, b) => b.score - a.score); inside a function that receives leaderboard as a parameter, and later code in the caller prints leaderboard expecting its original insertion order. What goes wrong, and what one-word change fixes it?
Show answer
sort reorders leaderboard in place and returns that same array, so ranked === leaderboard and the caller's array is now in score order. Changing sort to toSorted returns a new sorted array and leaves leaderboard in insertion order.
Exercise
What does this print? const xs = Object.freeze([10, 2, 33]); const ys = xs.toSorted(); console.log(ys, Object.isFrozen(ys));
Show answer
It prints [10, 2, 33] false. With no comparator, elements are compared as strings, and "10" < "2" < "33". The original is frozen but toSorted only reads it, and the new array it returns is not frozen.
Exercise
Write a toSorted call that orders people (objects with last and first string fields) by last name, then by first name, without changing people.
Show answer
const ordered = people.toSorted((a, b) => a.last.localeCompare(b.last) || a.first.localeCompare(b.first)); The || moves on to first names only when the last names compare equal (0).