Sub topic 2
Taking Control with Comparator Functions
This chapter assumes you know arrow functions, can read and write object properties, and have seen the previous chapter's point that sort() compares elements as strings by default. Here you replace that default with a rule of your own.
The Comparator Contract
A comparator is a function you pass to sort(). It takes two elements, a and b, and returns a number that tells the engine how they should be ordered.
| Return value | Meaning |
|---|---|
| Negative (for example `-1`) | `a` goes before `b` |
| Positive (for example `1`) | `a` goes after `b` |
| `0` | `a` and `b` are equal for sorting purposes |
Only the sign matters. Returning -42 means the same thing as returning -1. The engine calls your comparator many times during a sort, on whichever pairs its algorithm picks, so the comparator must answer the same way every time it sees the same pair.
Numbers
Subtraction gives the right sign directly. If a is smaller, a - b is negative, so a comes first.
const nums = [10, 1, 5, 100];
nums.sort();
console.log(nums); // [1, 10, 100, 5]
nums.sort((a, b) => a - b);
console.log(nums); // [1, 5, 10, 100]
nums.sort((a, b) => b - a);
console.log(nums); // [100, 10, 5, 1]To sort in descending order, swap the operands. Calling reverse() afterwards also works, but it costs an extra pass over the array.
Dates
Date objects convert to their millisecond timestamp when you subtract them, so the numeric pattern carries over unchanged.
const dates = [
new Date('2024-03-01'),
new Date('2023-12-25'),
new Date('2024-01-15')
];
dates.sort((a, b) => a - b);
console.log(dates.map(d => d.toISOString().slice(0, 10)));
// ['2023-12-25', '2024-01-15', '2024-03-01']If your dates are stored as ISO strings such as '2024-03-01', subtraction gives NaN. Either parse them with new Date(...) or compare them as strings. Plain string comparison happens to work for ISO dates because their characters run from the largest unit to the smallest.
Strings
Strings cannot be subtracted, so you write the three outcomes explicitly:
const words = ['pear', 'apple', 'fig'];
words.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
console.log(words); // ['apple', 'fig', 'pear']This compares UTF-16 code units, the same as the default sort, so 'Zebra' comes before 'apple'. A later chapter covers localeCompare and Intl.Collator, which give orderings that make sense to human readers.
Objects
To sort objects, pull out the property you care about and apply the matching pattern to it:
const products = [
{ name: 'Lamp', price: 35 },
{ name: 'Desk', price: 120 },
{ name: 'Pen', price: 2 }
];
products.sort((a, b) => a.price - b.price);
console.log(products.map(p => p.name)); // ['Pen', 'Lamp', 'Desk']Sorting by more than one property is covered in its own chapter.
Common Errors
Returning a Boolean
// Wrong: returns true or false
[3, 1, 2].sort((a, b) => a > b);true and false become 1 and 0. The comparator never returns a negative value, so the engine cannot tell "a before b" apart from "equal". The result depends on the engine and the input, and it may look correct on small arrays, which hides the bug. Use a - b instead.
NaN in the Data
If any value is NaN, or a property is missing so that a.price - b.price becomes NaN, the comparator returns neither a negative, a positive, nor zero. The ordering becomes inconsistent and the output is unpredictable. Clean or default the values first:
const items = [{ price: 5 }, {}, { price: 1 }];
items.sort((a, b) => (a.price ?? Infinity) - (b.price ?? Infinity));
console.log(items); // [{ price: 1 }, { price: 5 }, {}]Inconsistent Comparators
A comparator that uses randomness, such as () => Math.random() - 0.5, or that depends on outside state that changes during the sort, breaks the contract. The resulting order is not guaranteed, and shuffles built this way are biased. Use a Fisher–Yates shuffle for random ordering.
Exercises
Exercise
Write a comparator that sorts [{ t: '2024-05-01' }, { t: '2023-01-09' }] from newest to oldest, where t holds ISO date strings.
Show answer
(a, b) => new Date(b.t) - new Date(a.t). Putting b first gives descending order. Because these are ISO strings, (a, b) => (a.t < b.t ? 1 : a.t > b.t ? -1 : 0) also works.
Exercise
Why can [5, 2, 9].sort((a, b) => a > b) appear to work but still be considered a bug?
Show answer
It returns a boolean, which becomes 1 or 0 and is never negative. The engine cannot distinguish "less than" from "equal", so correct output on a given input is a coincidence that depends on the engine and its algorithm.
Exercise
An array of products has some items with no price property. What goes wrong with (a, b) => a.price - b.price, and how do you fix it?
Show answer
The missing price is undefined, so the subtraction produces NaN and the ordering becomes inconsistent. Supply a default, for example (a.price ?? Infinity) - (b.price ?? Infinity), which moves items without a price to the end.