⚡ JavaScript: Fix Array.sort Reordering Equal Items Unexpectedly
Every modern engine’s Array.prototype.sort is specified to be stable, meaning elements the comparator treats as equal keep their original relative order — but that guarantee only holds if the comparator itself behaves like a real comparator. A comparator that subtracts a field which can be undefined for some items doesn’t return 0 for ties, it returns NaN, and NaN breaks the total ordering sort relies on, producing results that look like instability even though the sort algorithm underneath is perfectly stable.
🔎 The Problem
const items = [
{ name: 'a', value: 3 },
{ name: 'b' }, // value is undefined
{ name: 'c', value: 3 },
];
items.sort((x, y) => x.value - y.value);
// undefined - 3 === NaN
// NaN is not a valid ordering result -> relative order of items
// involving 'b' is effectively unpredictable, even though sort()
// itself is stable for every comparison that returned a real number
✅ Fix: Make the Comparator Always Return a Real Signed Number
- Normalize missing or non-numeric fields to an explicit value before comparing, such as treating a missing
valueas 0 or as a dedicated “always last” sentinel, so the subtraction never produces NaN. - Return exactly 0 for genuine ties rather than letting an edge case produce NaN or an inconsistent sign, since a real 0 is what tells the stable sort to preserve original order for those items.
- Add an explicit secondary tie-breaker key, like original index or name, whenever the primary field can legitimately be equal across multiple items and the exact tie order matters to your output.
🚨 Why This Is Dangerous
- A sort that behaves inconsistently only on records with a missing field can pass every test built from complete sample data and still misbehave in production the first time a real record arrives with that field left out.
Array.sort kept its promise to be stable — the comparator that returned NaN broke its half of the bargain first.

