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?
Try this code:
HTML:
JavaScript code:
In JavaScript the sort() method's default behaviour is to sort values in an array alphabetically.
To sort by number you have to define a numeric sort function (which is very easy):
I am surprised why everyone recommends to pass a comparator funciton to
sort()
, that makes sorting really slow!To sort numbers, just create any TypedArray:
Here is my sort array function in the utils library:
For a normal array of elements values only:
For an array of objects: