0
0
JavascriptHow-ToBeginner · 3 min read

How to Sort Array in Descending Order in JavaScript

To sort an array in descending order in JavaScript, use the sort() method with a compare function that subtracts the first element from the second, like array.sort((a, b) => b - a). This tells JavaScript to order elements from largest to smallest.
📐

Syntax

The sort() method sorts the elements of an array in place. To sort numbers in descending order, provide a compare function:

  • array.sort((a, b) => b - a)

Here, a and b are two elements being compared. Subtracting b - a sorts from highest to lowest.

javascript
array.sort((a, b) => b - a);
💻

Example

This example shows how to sort a list of numbers from largest to smallest using sort() with a compare function.

javascript
const numbers = [5, 2, 9, 1, 5, 6];
numbers.sort((a, b) => b - a);
console.log(numbers);
Output
[9, 6, 5, 5, 2, 1]
⚠️

Common Pitfalls

Without a compare function, sort() converts elements to strings and sorts them alphabetically, which can give wrong results for numbers.

For example, [10, 2, 1].sort() results in [1, 10, 2], not numeric order.

Always provide a compare function for numeric sorting.

javascript
const arr = [10, 2, 1];
arr.sort();
console.log(arr); // Wrong: [1, 10, 2]

arr.sort((a, b) => b - a);
console.log(arr); // Correct: [10, 2, 1]
Output
[1, 10, 2] [10, 2, 1]
📊

Quick Reference

MethodDescriptionExample
sort()Sorts array elements alphabetically by default[3, 1, 2].sort() → [1, 2, 3] (as strings)
sort((a, b) => a - b)Sorts numbers in ascending order[3, 1, 2].sort((a,b) => a-b) → [1, 2, 3]
sort((a, b) => b - a)Sorts numbers in descending order[3, 1, 2].sort((a,b) => b-a) → [3, 2, 1]

Key Takeaways

Use array.sort((a, b) => b - a) to sort numbers in descending order.
Always provide a compare function when sorting numbers to avoid string-based sorting.
The sort() method changes the original array in place.
Without a compare function, sort() sorts elements as strings alphabetically.
Descending order means sorting from largest to smallest.