Home >Web Front-end >JS Tutorial >How Can I Correctly Sort an Integer Array in JavaScript to Find the Minimum and Maximum Values?
Getting the Most and the Least from an Integer Array: An Unexpected String Substitution
The task of finding the highest and lowest values within an array solely comprising integers seems deceptively straightforward. However, as one may discover, the native sort() method presents an unexpected hurdle. As it prioritizes alphabetical order by default, numerical sorting proves more challenging than anticipated. How can we overcome this hurdle and instruct the sort() function to focus on the integer values within the array elements?
Consider the following example:
var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray);
An intuitive expectation would lead us to expect output of 99, 104, 140000. However, the result is drastically different: 104, 140000, 99. This peculiar behavior stems from the sort() method's innate tendency to treat values as strings, rather than integers.
To remedy this issue, we can introduce a custom sorting function to explicitly handle numeric values. Here's how we can achieve that:
var numArray = [140000, 104, 99]; numArray.sort(function(a, b) { return a - b; }); console.log(numArray);
The sortNumber(a, b) function efficiently handles the numerical sorting we seek. By subtracting a from b, positive values push a to the right, ensuring that higher values appear later in the sorted array. Conversely, negative values prompt swaps, placing smaller values to the left. This custom sorting function empowers us to accurately sort arrays of integers, delivering both the highest and lowest values as intended.
The above is the detailed content of How Can I Correctly Sort an Integer Array in JavaScript to Find the Minimum and Maximum Values?. For more information, please follow other related articles on the PHP Chinese website!