Diagnosing Unstable Array.prototype.sort Results in JavaScript
Unexpected sort order, lost tie order, or mutated arrays? Diagnose comparator contract violations and ES2019 stability issues in JavaScript.
19 Jul 2026, 14:35 UTC

JavaScript's Array.prototype.sort can reorder equal elements, mutate the source array, or place NaN and undefined in implementation-dependent positions. If a sorted list changes between runs, loses insertion order for equal keys, or changes data you expected to remain read-only, the problem is usually a comparator that breaks the comparefn contract or an engine that predates ECMAScript 2019 stable-sort guarantees.
Takeaway: use a comparator that always returns -1, 0, or 1, handle NaN and undefined explicitly, sort a shallow copy when the original must not change, and verify stability in your exact target engine before relying on equal-key order.
Recognizable condition
- Sorted output differs between runs or environments.
- Equal keys lose insertion order.
- The source array is mutated although immutability was expected.
NaN,undefined, or missing compared properties appear in unexpected positions.
Cause and diagnostic table
| Symptom | Likely cause | First check |
|---|---|---|
| Order changes between runs | Comparator returns booleans or inconsistent values | Log comparator output for the same pair twice |
| Equal keys lose insertion order | Engine predates ES2019 or comparator is unstable | Check engine release notes; run a duplicate-key fixture |
| Original array changed | sort mutates in place | Compare the array reference before and after sorting |
NaN or undefined misplaced | Comparator does not handle non-numeric or missing values | Add explicit NaN and undefined branches |
Ordered checks
-
Confirm the comparator returns numbers, not booleans
A comparator such as
(a, b) => a.score > b.scorereturnstrueorfalse, which violates the comparefn contract. Rewrite it to return-1,0, or1for every input pair.Where: application code or test file. Permissions: none. Risk: none.
-
Verify comparator consistency
Call the comparator with the same arguments multiple times; results must match. It must not depend on mutable external state, because sort may call it an unpredictable number of times.
-
Check for
NaN,undefined, and missing propertiesComparisons involving
NaNreturn false for both<and>, which breaks ordering. Missing object properties produceundefinedoperands and inconsistent results. -
Confirm the engine supports stable sort
ECMAScript 2019 specifies stable
Array.prototype.sort, so equal elements preserve input order. Older or non-conforming engines may reorder equal elements. Check your engine's documentation; do not assume a polyfill matches native behavior. -
Check whether the original array must survive
Array.prototype.sortmutates the array it is called on. If the original order matters elsewhere, sort a copy instead.
Fixes tied to findings
- Comparator returns boolean: rewrite to return
-1,0, or1for every input pair. - Inconsistent comparator: remove external mutable state; make the comparison a pure function of its two arguments.
NaNorundefinedhandling: add explicit branches before numeric comparison.- Pre-ES2019 engine: do not rely on equal-key order; use a deterministic routine or upgrade the engine.
- Immutability required:
const sorted = [...items].sort(compare);
Example: total-order comparator
function compareByScore(a, b) {
const x = a.score;
const y = b.score;
if (Number.isNaN(x) && Number.isNaN(y)) return 0;
if (Number.isNaN(x)) return 1;
if (Number.isNaN(y)) return -1;
if (x === y) return 0;
return x < y ? -1 : 1;
}
Example: stability diagnostic fixture
// Run in Node or a browser console
const items = [
{ key: 1, id: 'a' },
{ key: 1, id: 'b' },
{ key: 1, id: 'c' },
];
const before = items.map((item) => item.id);
items.sort((a, b) => a.key - b.key);
const after = items.map((item) => item.id);
console.log(JSON.stringify({ before, after, stable: before.join('') === after.join('') }));
Expected check: stable is true in ES2019+ conforming engines. Risk: this mutates items; copy it first if you need the original order.
Escalation criteria
Escalate when nondeterministic ordering affects security, billing, or compliance and reproduces on an updated, conforming engine. Provide a minimal reproducible case to the platform maintainer, or replace Array.prototype.sort with a deterministic sorting routine that you control.
Limitations and verification
- Sorting orders data only; it does not validate, sanitize, or authorize access to sorted items.
- A comparator that throws or returns non-numeric values can abort sorting or produce implementation-defined behavior.
- Polyfills and transpiled sort helpers may not match native engine stability.
- Practical check: log
JSON.stringify(items.map(item => item.key))before and after sorting duplicate keys in the exact target engine. Equal keys should preserve input order in ES2019+ conforming engines. Assertoriginal === sortedis false when a copy was intended.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.