Sorting an Array of Integers Numerically
Sorting an array of integers numerically can be a challenge when the default sorting method treats them as strings. In this situation, the sort function sorts the values alphabetically, resulting in an incorrect numerical ordering.
To overcome this, a custom sorting function can be implemented to handle numeric sorts explicitly. The sortNumber function sorts elements in ascending order based on their numerical values:
numArray.sort(function(a, b) { return a - b; });
This function subtracts the first element (a) from the second element (b). If a is greater than b, the result will be positive, indicating that a should come after b in the sorted order. If a is less than b, the result will be negative, indicating that a should come before b. If a is equal to b, the result will be zero, indicating that their order should remain unchanged.
By using this custom sorting function, the array of integers will be sorted in ascending numerical order, ignoring the string values:
var numArray = [140000, 104, 99]; numArray.sort(sortNumber); console.log(numArray); // [99, 104, 140000]
The above is the detailed content of How to Sort an Array of Integers Numerically in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!