Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Is Array.sort stable in JavaScript

99 a stable sort, and the comparator that contradicts itself

fair

Sort a list of scores by score alone and show that items with equal scores keep the order they came in. Then show that the old decorate-with-the-index trick now produces the identical array, that sorting up and reversing is not the same as sorting down, and that undefined never reaches your comparator at all.

Stuck? Three hints, smallest first
  1. 1. Since ES2019 Array.prototype.sort is required to be stable, so equal elements keep their relative order. Nothing you write makes that happen.
  2. 2. The pre-2019 workaround was to sort { item, i } and use i as the final tiebreak. Run both and compare the results.
  3. 3. reverse flips everything, including the pairs your comparator called equal. A descending comparator does not.

The answer

const byScore = (a, b) => a.score - b.score;
const names = (list) => list.map((e) => e.name);

const entries = [
  { name: 'Chidi', score: 70 },
  { name: 'Amaka', score: 85 },
  { name: 'Bisi', score: 70 },
  { name: 'Tunde', score: 85 },
  { name: 'Ngozi', score: 61 },
];

const ascending = names([...entries].sort(byScore));

// The pre-2019 workaround: carry the original index and use it as the last word.
const decorated = names(
  entries
    .map((item, i) => ({ item, i }))
    .sort((a, b) => byScore(a.item, b.item) || a.i - b.i)
    .map(({ item }) => item)
);
const trickIsRedundant = same(ascending, decorated);

const upThenReversed = names([...entries].sort(byScore).reverse());
const straightDown = names([...entries].sort((a, b) => byScore(b, a)));

// A comparator that never returns 0 claims both orders at once.
const never0 = (a, b) => (a.score < b.score ? -1 : 1);
const contradiction = [never0(entries[0], entries[2]), never0(entries[2], entries[0])];

let sawUndefined = false;
const counting = (a, b) => {
  if (a === undefined || b === undefined) sawUndefined = true;
  return a - b;
};
const withHole = [3, undefined, 1].sort(counting).map((v) => (v === undefined ? 'undefined' : v));

const allEqual = names([...entries].sort(() => 0));

console.log('ascending :', ascending);
console.log('decorated :', decorated, '| redundant:', trickIsRedundant);
console.log('reversed  :', upThenReversed);
console.log('descending:', straightDown);

Output


      
7 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 7 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

7 checks

test('equal scores keep the order they arrived in', ascending, ['Ngozi', 'Chidi', 'Bisi', 'Amaka', 'Tunde']);
test('the decorate-by-index trick gives the identical answer, so it is now dead code', [decorated, trickIsRedundant], [ascending, true]);
test('sorting up and reversing flips the tied pairs as well', upThenReversed, ['Tunde', 'Amaka', 'Bisi', 'Chidi', 'Ngozi']);
test('a descending comparator leaves them alone, so the two disagree', straightDown, ['Amaka', 'Tunde', 'Chidi', 'Bisi', 'Ngozi']);
test('a comparator with no zero says Chidi is after Bisi and Bisi is after Chidi', contradiction, [1, 1]);
test('undefined is moved to the end without the comparator ever seeing it', [withHole, sawUndefined], [[1, 3, 'undefined'], false]);
test('a comparator that always returns 0 is the identity, which is stability restated', allEqual, ['Chidi', 'Amaka', 'Bisi', 'Tunde', 'Ngozi']);

Stability means that when your comparator returns 0, the two items come out in the order they went in. Since ES2019 every engine is required to provide it, which retired a generation of decorate-sort-undecorate helpers: the assertion above shows the trick and the plain sort producing byte-identical output. The practical payoff is that you can sort in stages — by name, then by market — and the earlier sort survives inside each group of the later one.

Stability is a promise the engine keeps only if your comparator returns 0 for equals. (a, b) => a.score < b.score ? -1 : 1 looks harmless and never returns 0, so it asserts a strict order between two equal items, and it asserts opposite things depending on which one it is handed first. That is not just unstable; it is a comparator the spec calls inconsistent, and an inconsistent comparator makes the whole result unspecified. The two-directional assertion is the cheapest test for it.

reverse after an ascending sort is the other thing people reach for. It gives descending order and it also reverses every tie, so the top of your leaderboard changes for no visible reason. Sort descending with a comparator instead. And undefined elements are always moved to the end by the spec, without your comparator ever being called on them, which is why a comparator that "handles undefined" is dead code — and why a hole in your data lands at the bottom of the table rather than where you expected.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.