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

ADVERTISEMENT

Conclusion

In this JavaScript Tutorial, we learned how to sort an array of numbers using sort() method.