In JavaScript, you can sort an array of numbers using the Array.prototype.sort() method. However, by default, the sort() method sorts elements as strings, which can lead to incorrect results for numbers (e.g., [10, 2, 30] would be sorted as [10, 2, 30] instead of [2, 10, 30]). To properly sort numbers, you need to provide a comparison function.
Here’s how you can do it:
Syntax
array.sort((a, b) => a - b);
Explanation of the Comparison Function
- The comparison function takes two arguments (
a and b), which represent two elements from the array.
- If the result of
a - b is:
- Negative:
a comes before b.
- Zero:
a and b remain in their current order.
- Positive:
b comes before a.
This ensures that the array is sorted numerically in ascending order.
Example: Sorting Numbers in Ascending Order
const numbers = [10, 5, 8, 1, 7];
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 5, 7, 8, 10]
Example: Sorting Numbers in Descending Order
To sort in descending order, reverse the comparison logic:
const numbers = [10, 5, 8, 1, 7];
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [10, 8, 7, 5, 1]
Important Notes
-
Mutating the Original Array: The sort() method modifies the original array in place. If you want to keep the original array unchanged, create a copy using slice() or the spread operator (...) before sorting:
const numbers = [10, 5, 8, 1, 7];
const sortedNumbers = [...numbers].sort((a, b) => a - b);
console.log(sortedNumbers); // Output: [1, 5, 7, 8, 10]
console.log(numbers); // Original array remains unchanged: [10, 5, 8, 1, 7]
-
Sorting Non-Numeric Arrays: If your array contains non-numeric values (e.g., strings or mixed types), additional handling may be required.
Final Answer
To sort an array of numbers in JavaScript:
- Use
array.sort((a, b) => a - b) for ascending order.
- Use
array.sort((a, b) => b - a) for descending order.
Example:
const numbers = [10, 5, 8, 1, 7];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 7, 8, 10]