Course contentsShow
← JavaScript
Lesson 899 of 2,72320. Array Iteration and TransformationFree lesson

Descending Order with Comparators

Reverse the comparator logic to sort arrays in descending order by swapping the subtraction operands.

Descending Order with Comparators

What you'll learn: How to reverse sort order by simply swapping the operands in your comparator function.


In the previous lesson, you learned to sort numbers in ascending order with a comparator like (a, b) => a - b. To flip the sort to descending order (largest to smallest), you just swap the operands: (a, b) => b - a.

Why This Works

Remember that a comparator tells sort() which element should come first:

  • A negative result means "a comes before b"
  • A positive result means "b comes before a"

When you write a - b, smaller values produce negative results and float to the front (ascending). When you write b - a, larger values of a produce negative results, so larger numbers move to the front (descending).

Simple Example

const numbers = [5, 2, 9, 1, 7];

// Ascending (smallest first)
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 5, 7, 9]

// Descending (largest first)
numbers.sort((a, b) => b - a);
console.log(numbers); // [9, 7, 5, 2, 1]

Think of it like reversing the comparison logic: instead of asking "how much smaller is a than b?", you ask "how much smaller is b than a?"—which puts the bigger values first.

When to Use

Anytime you need top-to-bottom ranking: highest scores, most recent dates, largest quantities, etc.

Key Takeaway: To sort in descending order, swap the subtraction operands in your comparator from a - b to b - a.