peirix peirix - 1 year ago 60
Javascript Question

How to sort an array of integers correctly

Trying to get the highest and lowest value from a 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[0] + ", " + numArray[numArray.length - 1]);

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

Any way to get the sort function to actually sort on integer value?

aks aks
Answer Source

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];