Sub topic 3
Comparators and the default string sort order
This chapter assumes you know how to index JavaScript arrays, have called Array.prototype.sort before, and can read arrow functions. Everything here applies to both sort and toSorted, because the two methods take the same optional comparator and follow the same ordering rules.
What happens without a comparator
When you call sort() with no arguments, JavaScript converts every element to a string and compares the strings by UTF-16 code unit. Numbers are no exception. 100 becomes "100", and "100" sorts before "40" because the character "1" comes before "4".
const scores = [40, 100, 1, 5];
console.log([...scores].sort()); // [1, 100, 40, 5]
const words = ["banana", "Apple", "cherry", "apple"];
console.log([...words].sort()); // ["Apple", "apple", "banana", "cherry"]
const mixed = ["b", "a", "C"];
console.log([...mixed].sort()); // ["C", "a", "b"]Uppercase letters have lower code units than lowercase ones, so "C" lands before "a". The default order is predictable, but it rarely matches what a person expects to see. undefined values are an exception to the string rule: they are never converted, and they always go to the end.
The comparator contract
A comparator is a function (a, b) => number that tells the sort how two elements relate:
| Return value | Meaning |
|---|---|
| Negative | `a` goes before `b` |
| Zero | Keep `a` and `b` in their current relative order |
| Positive | `a` goes after `b` |
Only the sign of the result matters. Since ES2019, sorting is required to be stable, so elements that compare as equal (zero) stay in their original order.
Common comparators
const nums = [40, 100, 1, 5];
console.log([...nums].sort((a, b) => a - b)); // [1, 5, 40, 100]
console.log([...nums].sort((a, b) => b - a)); // [100, 40, 5, 1]
const names = ["b", "a", "C"];
console.log([...names].sort((x, y) => x.localeCompare(y))); // ["a", "b", "C"]
const people = [
{ name: "Ada", age: 36 },
{ name: "Linus", age: 28 },
{ name: "Grace", age: 36 }
];
const byAgeThenName = [...people].sort(
(a, b) => a.age - b.age || a.name.localeCompare(b.name)
);
console.log(byAgeThenName.map((p) => p.name)); // ["Linus", "Ada", "Grace"]Subtraction works for numbers. For strings, use localeCompare, which orders text the way the language expects instead of by raw code units. To sort on more than one key, chain the keys with ||. When the first difference is 0, the || falls through to the next key.
Common errors
- Subtracting non-numbers.
"b" - "a"isNaN, and the sort treatsNaNas0, so string elements stay unsorted without any error. - Forgetting the comparator for numbers. This mistake is easy to miss, because
[3, 1, 2].sort()happens to come out right. The bug only appears once values have different numbers of digits. - Inconsistent comparators. A comparator must give the same answer every time it sees the same pair. Using
Math.random()inside a comparator does not shuffle the array fairly.
Exercise
What does [10, 9, 1, 2].sort() return, and what comparator would return the numbers in ascending numeric order?
Show answer
It returns [1, 10, 2, 9], because the elements are compared as the strings "1", "10", "2", and "9". Pass (a, b) => a - b to get [1, 2, 9, 10].
Exercise
Why is (a, b) => a > b an incorrect comparator?
Show answer
It returns a boolean, which becomes 1 or 0 and is never negative. The sort can never be told that a comes before b, so the order it produces is unreliable.