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?
Just building on all of the above answers, they can also be done in one line like this:
Try this code as below
to handle undefined, null, and NaN: Null behaves like 0, NaN and undefined goes to end.
I agree with aks, however instead of using
You should use
array.sort does a lexicographic sort by default, for a numeric sort, provide your own function. Here's a simple example:
Also note that sort works "in place", there's no need for the assignment.
This answer is equivalent to some of the existing answers, but ECMAScript 6 arrow functions provide a much more compact syntax that allows us to define an inline sort function without sacrificing readability:
It is supported in most browsers today.