Emmanuel Akinfulubi

JavaScriptArray

Write a compare function for sort() in JavaScript

Intermediate · 4 min read

sort can put anything in order: numbers, words, dates, products by price. It doesn't know what "in order" means for your data, though. You tell it by passing a small function called a comparator, or compare function. Write one well and every sort in your code becomes one short line.

In this tutorial you will write comparators that sort numbers up, sort numbers down, and sort words by their length. Then you will see why the very common (a, b) => a > b is not a comparator at all, even though it sometimes seems to work. You should know arrow functions and the basics of sort.

The one question a comparator answers

While sorting, sort keeps picking two items, calls them a and b, and asks your function: "should a come before b?" Your function answers with a number:

  • a negative number means yes, a goes first;
  • a positive number means no, b goes first;
  • zero means they count as equal, so leave them as they are.

Only the sign matters. -1 and -99 mean exactly the same thing.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

26 Writing a comparator

fair

Sort numbers up, then down, then sort words by length. Then work out why (a, b) => a > b is not a comparator.

Stuck? Three hints, smallest first
  1. 1. A comparator returns a negative number, zero, or a positive number. Only the sign is read.
  2. 2. a > b returns a boolean, which becomes 0 or 1. There is no way for it to say "a comes first".
  3. 3. a - b works for numbers and gives NaN for text, which is why strings need < and > or localeCompare.

Step 1: numbers, smallest first

For two numbers, a - b is negative when a is smaller, positive when a is bigger, and zero when they are equal. That is exactly the answer sort wants.

Step 1

const asc = (a, b) => a - b;
console.log(asc(1, 9));               // -8: 1 goes before 9
console.log(asc(9, 1));               // 8: 9 goes after 1
console.log([10, 9, 1].sort(asc));    // [ 1, 9, 10 ]

Giving the comparator a name like asc (short for ascending) makes the sort line read like a sentence.

Step 2: numbers, largest first

Swap the two letters and the signs flip, so the order flips too.

Step 2

const desc = (a, b) => b - a;
console.log([10, 9, 1].sort(desc)); // [ 10, 9, 1 ]

You don't need to sort and then reverse. Changing the comparator is enough.

Step 3: sort by something you work out

The comparator can compare anything it calculates from the items. To sort words by length, subtract the lengths.

Step 3

const byLength = (a, b) => a.length - b.length;
console.log(['ccc', 'a', 'bb'].sort(byLength)); // [ 'a', 'bb', 'ccc' ]

The same pattern sorts products by price (a.price - b.price) or people by age. You pick a number from each item and subtract.

Step 4: only the sign is read

To prove that the size of the answer doesn't matter, try two comparators that return different numbers with the same signs.

Step 4

console.log([3, 1, 2].sort((a, b) => Math.sign(a - b)));                // [ 1, 2, 3 ]
console.log([3, 1, 2].sort((a, b) => (a < b ? -99 : a > b ? 99 : 0))); // [ 1, 2, 3 ]

Math.sign turns any number into -1, 0 or 1. The second comparator returns -99 or 99. Both sort exactly like a - b, because sort only ever checks whether the answer is below, above or equal to zero.

Step 5: the boolean mistake

Many people write (a, b) => a > b. It reads well, but look at what it returns.

Step 5

console.log(1 > 2, Number(1 > 2)); // false 0
console.log(2 > 1, Number(2 > 1)); // true 1

a > b gives true or false. When sort needs a number, true becomes 1 and false becomes 0. So this function can say "b goes first" (1) or "they are equal" (0). It can never say "a goes first", because it never returns a negative number.

What happens next depends on the JavaScript engine and on the input. The result may come out sorted, half sorted or unchanged. That makes it a nasty bug: it can pass on a small test list and fail on real data. Always return a number with the right sign.

Step 6: why a - b can't sort text

Subtraction only works on numbers. Subtract two strings and you get NaN, which means "not a number".

Step 6

console.log('b' - 'a'); // NaN
const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
console.log(['banana', 'apple'].sort(byText)); // [ 'apple', 'banana' ]

For text, compare with < and > and return -1, 1 or 0 yourself. The ? : chain reads: if a is smaller, -1; otherwise if a is bigger, 1; otherwise 0.

The full solution

The panel has all four comparators, sorts with each one, and prints the numbers that a boolean comparator really returns. Press Run and check that the -99 version sorts the same as Math.sign.

The answer

const asc = (a, b) => a - b;
const desc = (a, b) => b - a;
const byLength = (a, b) => a.length - b.length;
const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);

console.log('ascending  :', [10, 9, 1].sort(asc));
console.log('descending :', [10, 9, 1].sort(desc));
console.log('by length  :', ['ccc', 'a', 'bb'].sort(byLength));
console.log('--- only the sign matters ---');
console.log('Math.sign version:', [3, 1, 2].sort((a, b) => Math.sign(a - b)));
console.log('-99 and 99 work as well as -1 and 1:', [3, 1, 2].sort((a, b) => (a < b ? -99 : a > b ? 99 : 0)));
console.log('--- the boolean mistake ---');
console.log('1 > 2 is', 1 > 2, 'which as a number is', Number(1 > 2));
console.log('2 > 1 is', 2 > 1, 'which is', Number(2 > 1), '<- never negative, so nothing moves left');
console.log("'b' - 'a' is", 'b' - 'a', '<- so a - b cannot sort text');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a - b sorts ascending', [10, 9, 1].sort(asc), [1, 9, 10]);
test('b - a sorts descending', [10, 9, 1].sort(desc), [10, 9, 1]);
test('a computed key works the same way', ['ccc', 'a', 'bb'].sort(byLength), ['a', 'bb', 'ccc']);
test('only the sign is read, so Math.sign changes nothing', [3, 1, 2].sort((a, b) => Math.sign(a - b)), [1, 2, 3]);
test('and any negative number means the same as -1', [3, 1, 2].sort((a, b) => (a < b ? -99 : a > b ? 99 : 0)), [1, 2, 3]);
test('a > b can only ever return 0 or 1', [Number(1 > 2), Number(2 > 1)], [0, 1]);
test('so a boolean comparator can never ask for a swap leftwards', [1, 2].map((n) => Number(n > 99)).includes(-1), false);
test('subtracting strings gives NaN', Number.isNaN('b' - 'a'), true);
test('so text needs explicit comparisons', ['banana', 'apple'].sort(byText), ['apple', 'banana']);

A comparator answers one question: does a belong before b? Negative means yes, positive means no, zero means "either, leave them as they are". The magnitude is ignored, which is why a - b and Math.sign(a - b) sort identically.

(a, b) => a > b is the mistake worth recognising. A boolean coerces to 0 or 1, so the comparator can say "swap" or "equal" but never "move a earlier". Depending on the engine's algorithm and the input, the result may be sorted, partly sorted, or untouched — which makes it a bug that passes in testing and fails in production. Assert the arithmetic rather than the output, as above, because the output is genuinely engine-dependent.

Common mistakes

  • Returning a boolean. a > b never returns a negative number, so sort can't move a earlier. Return a - b for numbers.
  • Subtracting strings. 'b' - 'a' is NaN. Use < and >, or localeCompare, for text.
  • Sorting and then reversing to go backwards. It works, but (a, b) => b - a says what you mean in one step.

Try it yourself

  1. Sort ['kiwi', 'fig', 'banana'] longest first.
  2. Sort [{ price: 900 }, { price: 300 }, { price: 450 }] by price, cheapest first.
  3. Sort [3, -1, 2, -5] by distance from zero, so -1 comes first. (Hint: Math.abs.)

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.