Sub topic 2
Sort Stability and Why It Matters
This chapter assumes you can write a basic comparator such as (a, b) => a - b, and that you know sort() changes the original array while toSorted() returns a new one.
Sort Stability
A sort is stable when elements that compare as equal keep their original relative order. Since ES2019, the specification requires Array.prototype.sort and toSorted to be stable in every engine.
const people = [
{ name: 'Cy', age: 30 },
{ name: 'Bo', age: 25 },
{ name: 'Ana', age: 30 }
];
const byAge = people.toSorted((a, b) => a.age - b.age);
console.log(byAge.map(p => p.name)); // ['Bo', 'Cy', 'Ana']Cy and Ana are both 30. Cy came before Ana in the input, so Cy still comes before Ana in the output.
Sorting Objects by Multiple Keys
To sort by more than one key, chain comparisons with ||. A comparison that returns 0 is falsy, so the next key is checked only when the earlier keys are tied.
const people = [
{ name: 'Cy', age: 30 },
{ name: 'Bo', age: 25 },
{ name: 'Ana', age: 30 }
];
const sorted = people.toSorted(
(a, b) => b.age - a.age || a.name.localeCompare(b.name)
);
console.log(sorted.map(p => p.name)); // ['Ana', 'Cy', 'Bo']Because the sort is stable, you can also sort in passes: sort by the secondary key first, then by the primary key.
Sorting Strings for Humans
The default sort compares UTF-16 code units, so accented letters land after z. localeCompare and Intl.Collator follow the ordering rules of a language instead.
const words = ['zebra', 'éclair', 'apple'];
console.log(words.toSorted()); // ['apple', 'zebra', 'éclair']
console.log(words.toSorted((a, b) => a.localeCompare(b))); // ['apple', 'éclair', 'zebra']
const collator = new Intl.Collator(undefined, { numeric: true });
console.log(['item10', 'item2', 'item1'].sort(collator.compare)); // ['item1', 'item2', 'item10']When you sort large arrays, create one collator and reuse it. That is faster than calling localeCompare with options on every comparison.
Sorting Typed Arrays
Typed arrays such as Int32Array and Float64Array sort numerically by default, so you don't need a comparator for them.
const t = new Int32Array([10, 1, 5, 100]);
t.sort();
console.log(Array.from(t)); // [1, 5, 10, 100]Finding Values
| Method | Returns | Compares with | Finds NaN |
|---|---|---|---|
| `indexOf` | First index or -1 | `===` | No |
| `lastIndexOf` | Last index or -1 | `===` | No |
| `includes` | Boolean | SameValueZero | Yes |
const values = [1, NaN, 3, 1];
console.log(values.indexOf(NaN)); // -1
console.log(values.includes(NaN)); // true
console.log(values.lastIndexOf(1)); // 3Exercise
Write a comparator that sorts products by price ascending, and alphabetically by name when prices are equal.
Show answer
(a, b) => a.price - b.price || a.name.localeCompare(b.name)
Exercise
Why does [NaN].indexOf(NaN) return -1 while [NaN].includes(NaN) returns true?
Show answer
indexOf uses strict equality, and NaN === NaN is false. includes uses SameValueZero, which treats NaN as equal to itself.