Home >Web Front-end >JS Tutorial >How to Numerically Sort an Integer Array in JavaScript?
How to Achieve Numerical Sorting of an Integer Array
When encountering difficulties in extracting the highest and lowest values from an array of integers, it's important to understand that the sort function in JavaScript operates primarily on strings. To sort by numerical value, a custom sorting method is necessary.
To resolve this, introduce the sortNumber method, which handles numerical sorting:
var numArray = [140000, 104, 99]; numArray.sort(function(a, b) { return a - b; }); console.log(numArray);
This method compares the elements a and b, returning a positive value if a is greater than b, a negative value if a is less than b, and zero if they are equal. By subtracting b from a, the elements are sorted in ascending order.
By modifying the array using this method, we can achieve accurate numerical sorting, ensuring that its members are arranged in ascending order and the expected output is achieved: [99, 104, 140000].
The above is the detailed content of How to Numerically Sort an Integer Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!