Sorting numbers in JavaScript requires special attention because the Array.prototype.sort()
method treats array elements as strings by default.
Example: Basic Sorting
Here’s a step-by-step example:
let numbers = [40, 1, 5, 200];
// Ascending order
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 5, 40, 200]
// Descending order
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [200, 40, 5, 1]
Explanation
The Problem with Default Sorting
- numbers.sort();
- This will result in
[1, 200, 40, 5]
. - Why? Because
sort()
converts numbers to strings and sorts them lexicographically (e.g., “200” comes before “40”).
Using a Compare Function
- To sort numbers correctly, pass a compare function to
sort()
.The functiona - b
ensures:- Ascending Order: If
a < b
, it returns a negative value. - Descending Order: If
b < a
, it returns a positive value.
- Ascending Order: If
Use Case: Sorting a Mixed Array
If the array contains non-numeric values, you’ll need to filter or handle them appropriately:
let mixedArray = [40, "apple", 1, 5, 200, "banana"];
// Filter and sort numbers only
let sortedNumbers = mixedArray.filter(item => typeof item === "number").sort((a, b) => a - b);
console.log(sortedNumbers); // Output: [1, 5, 40, 200]
Sorting in Reverse
For reversing any sorted array:
let numbers = [1, 5, 40, 200];
numbers.reverse();
console.log(numbers); // Output: [200, 40, 5, 1]
Key Points to Remember
- Always provide a compare function for numeric sorting.
- Use
filter()
if the array contains mixed types. - Use
reverse()
for reversing the order after sorting.