Sub topic 4
Sort Stability and Why It Matters
This chapter assumes you can write a comparator function, which the previous chapter covered. You should also know the difference between sort (mutates the array) and toSorted (returns a new one). The examples use toSorted, so run them in Node.js 20 or later, or in a current browser. If your environment is older, replace arr.toSorted(fn) with [...arr].sort(fn).
What Stability Means
A sorting algorithm is stable if elements that compare as equal keep the order they had before the sort. "Equal" here means the comparator returned 0 for them. The elements themselves don't need to be identical. Two players with the same score are equal to a score comparator even though their names differ.
An unstable sort may place equal elements in any order. It might put them back in their original order, it might reverse them, or it might shuffle them depending on the array's size and contents.
Here is a leaderboard sorted by score, highest first:
const players = [
{ name: 'Ava', score: 90 },
{ name: 'Ben', score: 85 },
{ name: 'Cal', score: 90 },
{ name: 'Dee', score: 85 },
{ name: 'Eli', score: 95 }
];
const byScore = players.toSorted((a, b) => b.score - a.score);
console.log(byScore.map(p => `${p.name}:${p.score}`));
// ['Eli:95', 'Ava:90', 'Cal:90', 'Ben:85', 'Dee:85']Ava and Cal both have 90. Ava came before Cal in the input, so a stable sort keeps Ava first. The same goes for Ben and Dee. An unstable sort could legally return Cal before Ava. The scores would still be in order, but the ranking would change from one run to the next or from one browser to another.
The ES2019 Guarantee
Before ES2019, the ECMAScript specification let engines choose any algorithm for Array.prototype.sort, and engines made different choices:
| Engine (before 2018–2019) | Approach | Stable? |
|---|---|---|
| V8 (Chrome, Node.js) before v7.0 | Insertion sort for arrays of 10 or fewer elements, quicksort for longer ones | Only for short arrays |
| SpiderMonkey (Firefox) | Merge sort | Yes |
| JavaScriptCore (Safari) | Merge sort | Yes |
The V8 behavior caused a particular kind of bug. Code tested on a 5-item array behaved correctly, then reordered ties once production data passed 10 items, and only in Chrome and Node.js. V8 7.0 (Chrome 70, Node.js 11) replaced its sort with TimSort, which is stable. ES2019 then made stability a requirement of the specification.
Today, every conforming engine returns a stable result from:
Array.prototype.sortArray.prototype.toSorted(ES2023), which is defined in terms of the same sorting stepsTypedArray.prototype.sortandtoSorted
You Can Check It Yourself
Stability is hard to see on tiny arrays, because even unstable algorithms often happen to keep order on a few elements. This test builds 1,000 objects with only three distinct keys, so there are many ties, and then checks that the ids inside each group are still increasing:
const items = Array.from({ length: 1000 }, (_, id) => ({ id, group: id % 3 }));
const sorted = items.toSorted((a, b) => a.group - b.group);
const isStable = sorted.every((item, i) =>
i === 0 ||
item.group !== sorted[i - 1].group ||
item.id > sorted[i - 1].id
);
console.log(sorted.slice(0, 4).map(x => x.id)); // [0, 3, 6, 9]
console.log(isStable); // trueOn a modern engine this prints true. On V8 before 7.0, the same check with sort would usually print false.
Why It Matters in Practice
Preserving an Order You Already Have
Arrays often arrive already in a meaningful order: newest first from an API, insertion order from a form, or relevance order from a search backend. A stable sort lets you reorder by one field without losing that existing order among the ties.
Suppose messages arrive in chronological order and you want unread messages on top:
const messages = [
{ id: 1, read: true, text: 'Welcome' },
{ id: 2, read: false, text: 'Invoice' },
{ id: 3, read: true, text: 'Reminder' },
{ id: 4, read: false, text: 'Alert' }
];
const unreadFirst = messages.toSorted((a, b) => Number(a.read) - Number(b.read));
console.log(unreadFirst.map(m => m.id)); // [2, 4, 1, 3]Within the unread group, 2 still comes before 4. Within the read group, 1 still comes before 3. The chronological order survives without being written into the comparator.
Sorting in Passes
Stability also lets you sort by several keys one pass at a time. You sort by the least important key first and by the most important key last. Each later pass keeps the order from earlier passes among its own ties.
const tasks = [
{ title: 'Write docs', priority: 2 },
{ title: 'Fix bug', priority: 1 },
{ title: 'Deploy', priority: 2 },
{ title: 'Add tests', priority: 1 }
];
// Pass 1: secondary key (title)
const byTitle = tasks.toSorted((a, b) => a.title.localeCompare(b.title));
// Add tests, Deploy, Fix bug, Write docs
// Pass 2: primary key (priority)
const byPriorityThenTitle = byTitle.toSorted((a, b) => a.priority - b.priority);
console.log(byPriorityThenTitle.map(t => t.title));
// ['Add tests', 'Fix bug', 'Deploy', 'Write docs']The pass order is the opposite of what most people expect, and getting it wrong is a common bug. If you sort by priority first and then by title, the result is sorted only by title, and the priority order is mostly lost.
This technique works best when the passes happen at different times. A sortable table in a user interface is the usual case. The user clicks "Title", then clicks "Priority", and the stable sort keeps rows with equal priority in title order with no extra code. When you know every key in advance, one comparator that checks all the keys is faster and clearer. The next chapter covers that approach.
Predictable Output and Tests
An unstable sort can return a different order for equal elements on different runs, engines, or array sizes. That leads to flaky snapshot tests, rows that jump around when a list re-renders, and pagination that shows the same item on two pages. Stability makes the output a deterministic function of the input and the comparator.
When Stability Doesn't Help You
Inconsistent Comparators
The stability guarantee only holds when the comparator is consistent. A consistent comparator returns a negative number, zero, or a positive number, answers the same way every time for the same pair, and is transitive. If the comparator breaks these rules, the specification says the sort order is implementation-defined. The engine can return any permutation, and the stability guarantee no longer applies.
The most common way to break the rules is to return a boolean:
const nums = [3, 1, 2];
// Wrong: returns true/false, coerced to 1/0. It never returns a negative value.
nums.toSorted((a, b) => a > b);
// Right
nums.toSorted((a, b) => a - b); // [1, 2, 3]a > b returns false (coerced to 0) whenever a < b. The sort is then told that 1 and 3 are "equal" in one direction and "greater" in the other. Depending on the engine and the input, the result may be correct, partly sorted, or different across browsers. In Chrome, the boolean version does not sort [3, 1, 2] correctly, even though this same pattern seemed to work in older engines.
Two other comparators also break the rules:
- A random comparator such as
() => Math.random() - 0.5, which people use as a shuffle. It is inconsistent and produces a biased shuffle. Use a Fisher–Yates shuffle instead. - A comparator that reads mutable state, such as a value that changes during the sort.
Ties You Didn't Intend
Stability keeps the input order among ties. If that input order is arbitrary, for example rows a database returned without ORDER BY, the output is stable but still arbitrary. When the order of ties matters to users, add a tiebreaker key such as an id or a timestamp to the comparator. Don't depend on whatever order the data happened to arrive in.
Elements the Comparator Never Sees
The spec sorts undefined values and holes in sparse arrays separately. undefined values go to the end, followed by holes, and the comparator is never called for them. Stability has nothing to say about where they land relative to your other values:
const arr = [3, undefined, 1, , 2];
console.log(arr.toSorted((a, b) => a - b)); // [1, 2, 3, undefined, undefined]toSorted turns the hole into undefined. sort keeps it as a hole at the very end.
Primitives
For an array of numbers or strings, equal elements can't be told apart, so stability has no visible effect. It matters only when the elements carry more data than the sort key, which in practice means objects, or arrays of tuples sorted by one position.
Stable Sorting on Old Runtimes
If you must support an engine older than ES2019, you can make any sort stable with the decorate–sort–undecorate pattern. Attach each element's original index, use that index as the final tiebreaker, and then strip it off:
function stableSort(array, compare) {
return array
.map((value, index) => ({ value, index }))
.sort((a, b) => compare(a.value, b.value) || a.index - b.index)
.map(entry => entry.value);
}
const result = stableSort(
[{ k: 1, tag: 'a' }, { k: 0, tag: 'b' }, { k: 1, tag: 'c' }],
(a, b) => a.k - b.k
);
console.log(result.map(x => x.tag)); // ['b', 'a', 'c']With the index as a tiebreaker, no two elements ever compare as equal, so the algorithm's stability doesn't matter. The cost is an extra object per element and two extra passes over the array. On modern engines this wrapper is unnecessary, so leave it out unless you have a real legacy target.
Summary
| Question | Answer |
|---|---|
| What is preserved? | Relative order of elements the comparator calls equal (returns `0`) |
| Since when is it guaranteed? | ES2019. V8 has been stable since 7.0 (Chrome 70, Node.js 11) |
| Which methods? | `sort`, `toSorted`, and their typed-array versions |
| When does the guarantee break? | When the comparator is inconsistent, for example returning booleans or random values |
| Main uses | Keeping an existing order, sorting in passes, deterministic output |
| Old-engine workaround | Decorate with the index and use it as the last tiebreaker |
Exercise
You have an array of products already ordered by popularity (most popular first). You sort it with products.toSorted((a, b) => a.price - b.price). Two products cost $20. In what order will they appear, and would that be guaranteed in Node.js 10?
Show answer
They appear in their original popularity order, with the more popular one first, because ES2019 requires a stable sort and the comparator returns 0 for equal prices. Node.js 10 used V8's pre-7.0 sort, which was unstable for arrays longer than 10 elements, so the order was not guaranteed there. (toSorted also didn't exist in Node.js 10. You would have used [...products].sort(...).)
Exercise
A developer wants employees ordered by department, and alphabetically by name within each department. They write emps.sort(byDepartment); emps.sort(byName);. What is wrong, and how do you fix it using only these two comparators?
Show answer
The passes are in the wrong order. The last sort decides the primary order, so the result is sorted by name, and department order survives only among employees with the same name. Sort by the secondary key first: emps.sort(byName); emps.sort(byDepartment);. The stable second pass keeps the name order inside each department.
Exercise
Why does [5, 1, 4].sort((a, b) => a > b) give no stability guarantee, and possibly no correct order at all?
Show answer
The comparator returns a boolean, which is coerced to 1 or 0, so it never returns a negative value. When a < b it reports the two as equal, but when called with the arguments swapped it reports one as greater. That makes it inconsistent, and the specification then calls the result implementation-defined. Engines may return a wrong or differing order. Use (a, b) => a - b.