Friday, April 27, 2018

javascript - How to sort an array of integers correctly



Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought.





var numArray = [140000, 104, 99];
numArray = numArray.sort();
alert(numArray)






I'd expect this to show 99, 104, 140000. Instead it shows 104, 140000, 99. So it seems the sort is handling the values as strings.



Is there a way to get the sort function to actually sort on integer value?


Answer



By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -






function sortNumber(a, b) {
return a - b;
}

var numArray = [140000, 104, 99];
numArray.sort(sortNumber);

console.log(numArray);






In ES6, you can simplify this with arrow functions:



numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort






Documentation:



Mozilla Array.prototype.sort() recommends this compare function for arrays that don't contain Infinity or NaN. (Because Inf - Inf is NaN, not 0).



Also examples of sorting objects by key.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...