Sub topic 4
Sort Stability and Why It Matters
This chapter assumes you can write a comparator function, you know that sort mutates while toSorted returns a copy, and you are comfortable with arrays of objects. Here you will learn what a stable sort is, what the language guarantees, and how that guarantee affects the code you write.
What Stability Means
A sort is stable when elements that compare as equal keep the order they had before sorting. Your comparator decides what "equal" means: any pair for which it returns 0 counts as a tie, and a stable sort leaves each tie in its original relative order.
Stability only shows up when elements can be equal under the comparator but still differ in some way you can see. If you sort plain numbers, two 5s look identical, so their order does not matter. If you sort objects by one property, two objects with the same priority can still have different ids, so it does matter which one comes first.
const tickets = [
{ id: 'A', priority: 2 },
{ id: 'B', priority: 1 },
{ id: 'C', priority: 2 },
{ id: 'D', priority: 1 }
];
const byPriority = tickets.toSorted((a, b) => a.priority - b.priority);
console.log(byPriority.map(t => t.id)); // ['B', 'D', 'A', 'C']In the input, B comes before D and A comes before C. The comparator returns 0 for each of those pairs, so a stable sort keeps them in that order. If the tickets arrived in that order, sorting by priority leaves each priority group in first-come, first-served order without any extra code.
What the Language Guarantees
Before ES2019, the specification let engines choose any sorting algorithm, stable or not. V8, the engine in Chrome and Node.js, used an unstable quicksort for arrays longer than 10 elements. Code that happened to work on a small test array could reorder ties once the array grew.
Since ES2019, Array.prototype.sort must be stable. The guarantee also covers toSorted and the typed array sort methods. Every current browser and supported Node.js version follows it, so you can rely on it unless you target very old engines.
Sorting in Passes
Stability lets you sort by several keys by running several sorts in a row. Sort by the least important key first and the most important key last. Each later pass keeps the order of the earlier one inside its own ties.
const people = [
{ name: 'Cy', age: 30 },
{ name: 'Bo', age: 25 },
{ name: 'Ana', age: 30 },
{ name: 'Dee', age: 25 }
];
const byName = people.toSorted((a, b) => a.name.localeCompare(b.name));
const byAgeThenName = byName.toSorted((a, b) => a.age - b.age);
console.log(byName.map(p => p.name)); // ['Ana', 'Bo', 'Cy', 'Dee']
console.log(byAgeThenName.map(p => p.name)); // ['Bo', 'Dee', 'Ana', 'Cy']The second pass sorts by age only. The two 25-year-olds and the two 30-year-olds are ties, so each pair stays in the alphabetical order from the first pass.
Running sorts in passes is handy when the user picks the order interactively, for example by clicking table column headers one after another. The current order of the table then acts as the tie-breaker. When the keys are fixed in code, a single comparator that combines them is usually clearer and faster. The next chapter covers that approach.
Common Mistakes
These errors break the ordering you expect even though the sort itself is stable.
| Mistake | Why it fails | Fix |
|---|---|---|
| Comparator returns a boolean, such as `(a, b) => a.age > b.age` | `false` becomes `0` and `true` becomes `1`, and the result is never negative, so the comparator is inconsistent and the order depends on the engine | Return a number: `a.age - b.age` |
| Running passes from most to least important key | The last pass decides the main order and overrides the earlier passes | Sort by the least important key first |
| Relying on input order that is itself random | Stability keeps the order you give it, and a random input order produces random ties | Add an explicit tie-breaker key such as `id` |
| Assuming stability on a pre-ES2019 engine | Old engines could reorder ties in long arrays | Add explicit tie-breakers, or use a known stable library sort |
Exercises
Exercise
You have const tasks = [{ t: 'x', done: true }, { t: 'y', done: false }, { t: 'z', done: true }, { t: 'w', done: false }]. What does tasks.toSorted((a, b) => a.done - b.done).map(k => k.t) return, and why?
Show answer
It returns ['y', 'w', 'x', 'z']. Booleans convert to numbers in subtraction, so false (0) sorts before true (1). The comparator returns 0 for tasks with the same done value, so the stable sort keeps y before w and x before z, matching their input order.
Exercise
You want a product list ordered by category and, within each category, by price from lowest to highest. You plan to do it with two stable toSorted passes. Which key should the first pass use, and what goes wrong if you reverse the order?
Show answer
The first pass should sort by price and the second by category. The last pass sets the main grouping, and stability keeps the earlier price order within each category. If you sort by category first and price second, the result is ordered by price overall and the categories end up mixed together.