sort() with Comparator Functions
You'll learn how to control exactly how sort() arranges your array by passing in a custom comparison function.
The Problem with Default sort()
By default, sort() converts everything to strings and sorts alphabetically. This works fine for words, but causes bizarre results with numbers:
const numbers = [10, 5, 40, 25, 100];
numbers.sort();
console.log(numbers); // [10, 100, 25, 40, 5] — Wrong!
Why? Because as strings, "10" comes before "5" alphabetically.
The Solution: Comparator Functions
A comparator function is a callback you pass to sort() that tells it how to compare two elements. It receives two arguments (often called a and b) and must return:
- A negative number if
ashould come beforeb - A positive number if
bshould come beforea - Zero if they're equal (order doesn't matter)
// Sort numbers ascending
const numbers = [10, 5, 40, 25, 100];
numbers.sort(function(a, b) {
return a - b; // If a < b, result is negative → a comes first
});
console.log(numbers); // [5, 10, 25, 40, 100] — Correct!
Reverse (Descending) Order
Just flip the subtraction:
numbers.sort(function(a, b) {
return b - a; // Larger numbers first
});
console.log(numbers); // [100, 40, 25, 10, 5]
Think of It Like a Judge
The comparator is a judge comparing two contestants. It tells sort(): "Put this one first" (negative), "Put that one first" (positive), or "They're tied" (zero). The sort() method handles all the shuffling based on your verdicts.
Key Takeaway: Pass a comparator function to sort() to control comparison logic—use (a, b) => a - b for numeric ascending, (a, b) => b - a for descending, or write custom logic for complex sorting rules.