JavaScript – Sort a Numeric Array
To sort an array of numbers in JavaScript, call sort() method on this numeric array. sort() method sorts the array in-place and also returns the sorted array, where the numbers are sorted in ascending order.
Since, the sort operation happens in-place, the order of the elements in input array are modified.
When sorting numbers, sort() method considers numbers as strings and considers 1000 less than 2. To override this behaviour, we need to pass a comparison function that returns the difference of the two numbers compared during sorting.
sort() method by default sorts in ascending order. To get the descending order, use reverse() method on the sorted array.
Example
In the following example, we have taken a numeric array in inputArr
. We sort this array using sort() method and store the resulting array in sortedArr
.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<pre id="output"></pre>
<script>
var inputArr = [24, 6, 3, 87, 9];
displayOutput = 'Input Array : ' + inputArr;
var sortedArr = inputArr.sort((a, b) => a - b);
displayOutput += '\nSorted Array : ' + sortedArr;
document.getElementById('output').innerHTML = displayOutput;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to sort an array of numbers using sort() method.