JavaScript – Sort array of numbers

To sort an array of numbers in JavaScript, you can use the built-in sort() method. However, it’s important to note that the sort() method sorts the elements as strings by default, so you’ll need to provide a comparison function for numerical sorting.

Sort in ascending order

const numbers = [5, 3, 8, 1, 2];

// Sorting in ascending order
numbers.sort((a, b) => a - b);

console.log(numbers); // Output: [1, 2, 3, 5, 8]

In the above example, we have provided a callback function to sort() that takes two parameters a & b, If the result of a - b is negative, a is sorted before b (indicating that a is less than b). If the result is positive, b is sorted before a. If the result is zero, their order remains unchanged.

Sort in descending order

const numbers = [5, 3, 8, 1, 2];

// Sorting in descending order
numbers.sort((a, b) => b - a);

console.log(numbers); // Output: [8, 5, 3, 2, 1]

In the above example, we have used the comparison function in sort() which works like this. If b - a is negative, it means b is less than a, and a will be placed before b. If b - a is positive, b will be placed before a.


Similar Reads