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
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce() In the… Read more: JavaScript – Convert an array to an object
- JavaScript – Shuffle an array in a random orderTo shuffle an array in random order in JavaScript, you can use the sort() function with Math.random() or use the map() & sort() function. Let’s… Read more: JavaScript – Shuffle an array in a random order