Sorting an Array of Integers: Beyond Alphabetical Ordering
In attempting to retrieve the highest and lowest values from an array of integers, you may have encountered an unexpected behavior: the sort function appears to be sorting the elements as strings. To overcome this issue, we need a sorting mechanism that considers integer values.
Understanding the Default Sort
By default, the sort method in JavaScript performs an alphabetical sort. This means that elements are compared as strings and arranged in lexicographical order. In the case of integers, this can lead to incorrect results, as the comparison is based on the string representation of the numbers rather than their actual values.
Solution: Custom Numeric Sort Function
To address this limitation, we can define a custom sorting function that focuses on comparing the integer values of array elements. Here's a simple example:
var numArray = [140000, 104, 99]; numArray.sort(function(a, b) { return a - b; }); console.log(numArray);
The provided sorting function (named sortNumber or similar) takes two parameters, a and b, representing the two elements being compared. To sort the array in ascending order, we simply subtract a from b. If the result is positive, a should come after b; if negative, a should come before b.
Results
By utilizing the custom sorting function, we get the correct result:
[99, 104, 140000]
The array elements are now sorted in ascending numerical order by their integer values, as intended.
The above is the detailed content of How Do I Correctly Sort an Array of Integers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!