Writing a Numeric Comparator
You'll learn how to create a comparator function that tells sort() exactly how to arrange numbers in ascending order.
The Problem We're Solving
As you saw in the previous lesson, sort() converts everything to strings by default, which makes numbers sort incorrectly (like "10" coming before "2"). A comparator function is your solution: it's a custom function you pass to sort() that compares two elements and tells sort() which should come first.
How Comparators Work
A comparator receives two parameters (often called a and b) and must return:
- A negative number if
ashould come beforeb - Zero if they're equal (order doesn't matter)
- A positive number if
ashould come afterb
Think of it like a judge deciding between two contestants: thumbs down means the first wins, thumbs sideways means tie, thumbs up means the second wins.
Writing a Numeric Comparator
Here's the classic numeric comparator for ascending order:
const numbers = [10, 2, 35, 7];
numbers.sort((a, b) => a - b);
console.log(numbers); // [2, 7, 10, 35]
Why does a - b work perfectly?
- If
ais smaller thanb, subtraction gives a negative number →acomes first - If they're equal, subtraction gives zero → order stays the same
- If
ais larger thanb, subtraction gives a positive number →bcomes first
For descending order, just flip it: b - a.
Key Takeaway: A numeric comparator returns a - b for ascending order, using subtraction's natural negative/zero/positive results to guide the sort algorithm.