JavaScript Program to Sort Array in Descending Order
array.sort((a, b) => b - a) to sort a JavaScript array in descending order.Examples
How to Think About It
Algorithm
Code
const arr = [3, 1, 4, 2]; arr.sort((a, b) => b - a); console.log(arr);
Dry Run
Let's trace sorting [3, 1, 4, 2] in descending order using the comparison function.
Initial array
[3, 1, 4, 2]
Compare 3 and 1
b - a = 1 - 3 = -2 (negative), so 3 stays before 1
Compare 3 and 4
b - a = 4 - 3 = 1 (positive), so 4 moves before 3
Compare 1 and 2
b - a = 2 - 1 = 1 (positive), so 2 moves before 1
Final sorted array
[4, 3, 2, 1]
| Comparison | Result | Action |
|---|---|---|
| 3 vs 1 | 1 - 3 = -2 | 3 before 1 |
| 3 vs 4 | 4 - 3 = 1 | 4 before 3 |
| 1 vs 2 | 2 - 1 = 1 | 2 before 1 |
Why This Works
Step 1: Sorting with a comparison function
The sort method can take a function that compares two elements to decide their order.
Step 2: Descending order logic
By subtracting b - a, the function returns a positive number if b is larger, so it places b before a.
Step 3: In-place sorting
The sort method changes the original array to the sorted order.
Alternative Approaches
const arr = [3, 1, 4, 2]; arr.sort((a, b) => a - b); arr.reverse(); console.log(arr);
const arr = [3, 1, 4, 2]; for(let i = 0; i < arr.length; i++) { for(let j = 0; j < arr.length - i - 1; j++) { if(arr[j] < arr[j + 1]) { [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; } } } console.log(arr);
Complexity: O(n log n) time, O(1) space
Time Complexity
The built-in sort method uses an efficient sorting algorithm like Timsort or QuickSort, which runs in O(n log n) time on average.
Space Complexity
Sorting is done in-place, so extra space is minimal, O(1).
Which Approach is Fastest?
Using sort((a, b) => b - a) is fastest and simplest; reversing after sorting adds extra steps; manual sorting is slow and mainly for learning.
| Approach | Time | Space | Best For |
|---|---|---|---|
| sort((a, b) => b - a) | O(n log n) | O(1) | Fast and simple for all arrays |
| sort ascending + reverse | O(n log n) | O(1) | Simple but slightly less efficient |
| Manual bubble sort | O(n²) | O(1) | Learning and very small arrays |
sort when sorting numbers to avoid incorrect order.sort() without a comparison function sorts numbers as strings, causing wrong order.