Sub topic 12
Sorting Correctly with Comparator Functions
This chapter assumes you know arrow functions, how to read object properties, and how array callbacks receive their arguments. It also assumes you know that some methods mutate the array they are called on. Here you will learn how sort decides element order and how to make it put elements in the order you want.
The default sort compares strings
When you call sort() with no arguments, JavaScript converts every element to a string. It then orders those strings by UTF-16 code units. That works for plain lowercase words. It gives surprising results for numbers:
const nums = [10, 1, 5, 100, 25];
console.log([...nums].sort()); // [1, 10, 100, 25, 5]As strings, "100" comes before "25" because the character "1" comes before "2". The same rule puts uppercase letters before all lowercase letters, so "Zoe" sorts ahead of "adam".
Writing a comparator
A comparator is a function (a, b) => number that you pass to sort. It tells sort how any two elements relate:
| Return value | Meaning |
|---|---|
| Negative | `a` goes before `b` |
| Positive | `a` goes after `b` |
| Zero | Keep their current relative order |
To sort numbers, subtract one from the other:
const nums = [10, 1, 5, 100, 25];
console.log(nums.toSorted((a, b) => a - b)); // [1, 5, 10, 25, 100]
console.log(nums.toSorted((a, b) => b - a)); // [100, 25, 10, 5, 1]The comparator only needs to return the right sign. It does not need to return exactly -1 or 1.
Sorting strings and objects
For human-readable text, use localeCompare. It handles case and accented letters according to language rules:
const names = ['zoe', 'Émile', 'adam', 'Ben'];
console.log(names.toSorted((a, b) => a.localeCompare(b)));
// ['adam', 'Ben', 'Émile', 'zoe']To sort objects, compare one of their properties. To sort by more than one key, fall back to the next key when the first comparison returns 0:
const people = [
{ name: 'Cleo', age: 24 },
{ name: 'Ana', age: 31 },
{ name: 'Ben', age: 24 }
];
const sorted = people.toSorted(
(a, b) => a.age - b.age || a.name.localeCompare(b.name)
);
console.log(sorted.map(p => p.name)); // ['Ben', 'Cleo', 'Ana']The || operator only evaluates the name comparison when the age difference is 0, because 0 is falsy.
Common mistakes
- Returning a boolean. A comparator like
(a, b) => a > breturnstrueorfalse, which become 1 and 0. It never returns a negative value, so the result depends on the engine and is often wrong. Return a number. - Subtracting strings.
'b' - 'a'isNaN. UselocaleComparefor text. - Forgetting about mutation. Calling
data.sort()on an array that other code shares reorders it for every part of the program that uses it. - Relying on unstable order. Since ES2019,
sortis guaranteed to be stable: elements that compare as equal keep their original order. Multi-key sorts can rely on this.
Exercise
Sort the array [3, 20, 100, 4] in descending numeric order without modifying it. What does [3, 20, 100, 4].sort() return instead?
Show answer
Use arr.toSorted((a, b) => b - a), which returns [100, 20, 4, 3] and leaves arr unchanged. Plain sort() compares the elements as strings and returns [100, 20, 3, 4].
Exercise
Why is (a, b) => a.price > b.price an incorrect comparator, and what should you write instead?
Show answer
It returns a boolean, which converts to 1 or 0 and never to a negative number, so sort cannot tell when a should come first. Write (a, b) => a.price - b.price.