snippetjavascriptCritical
How can I sort an array of integers?
Viewed 0 times
arrayhowsortintegerscan
Problem
I am trying to get the highest and lowest value from an array that I know will contain only integers, and it seemed to be harder than I thought.
I'd expect this to show
Is there a way to get the sort function to sort on the integer value of each array element?
var numArray = [140000, 104, 99];
numArray = numArray.sort();
console.log(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 sort on the integer value of each array element?
Solution
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -
Documentation:
Mozilla
Also examples of sorting objects by key.
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});
console.log(numArray);
Documentation:
Mozilla
Array.prototype.sort() recommends this compare function for arrays that don't contain Infinity or NaN. (Because Infinity - Infinity is NaN, not 0).Also examples of sorting objects by key.
Context
Stack Overflow Q#1063007, score: 2057
Revisions (0)
No revisions yet.