How to Sort Array of Numbers in JavaScript Quickly and Correctly
To sort an array of numbers in JavaScript, use the
sort() method with a compare function like (a, b) => a - b. This ensures numbers are sorted in numeric order instead of as strings.Syntax
The sort() method sorts the elements of an array in place and returns the sorted array. When sorting numbers, you should provide a compare function to define the sort order.
array.sort(compareFunction): Sorts the array using thecompareFunction.compareFunction(a, b): Returns a negative number ifashould come beforeb, zero if they are equal, or a positive number ifashould come afterb.
javascript
array.sort((a, b) => a - b);
Example
This example shows how to sort an array of numbers in ascending order using the sort() method with a compare function.
javascript
const numbers = [40, 100, 1, 5, 25, 10]; numbers.sort((a, b) => a - b); console.log(numbers);
Output
[1, 5, 10, 25, 40, 100]
Common Pitfalls
Without a compare function, sort() converts numbers to strings and sorts them lexicographically, which leads to incorrect order for numbers.
For example, [40, 100, 1].sort() results in [1, 100, 40], which is wrong numerically.
javascript
const arr = [40, 100, 1]; console.log(arr.sort()); // Wrong: [1, 100, 40] // Correct way: console.log(arr.sort((a, b) => a - b)); // Correct: [1, 40, 100]
Output
[1, 100, 40]
[1, 40, 100]
Quick Reference
- Use:
array.sort((a, b) => a - b)for ascending numeric sort. - Use:
array.sort((a, b) => b - a)for descending numeric sort. - Remember: Without a compare function, numbers sort as strings.
Key Takeaways
Always provide a compare function to sort numbers correctly in JavaScript.
The compare function should return a negative, zero, or positive value to define order.
Without a compare function, numbers are sorted as strings, causing wrong order.
Use (a, b) => a - b for ascending and (a, b) => b - a for descending numeric sort.