views:

139

answers:

4

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?

+4  A: 

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 = numArray.sort(sortNumber);
alert(numArray[0] + ", " + numArray[numArray.length - 1]);
muteW
Nice. But is there really no out-of-the-box way to get a numerical sort from javascript?
peirix
None that I know of, you could inline the function in the sort call for brevity's sake but there exists no other way (unless ofcourse you write your own function / use an existing library).
muteW
A: 

You can pass into .sort() a function that tells it how to sort it. Here's a tutorial on this.

Ólafur Waage
+2  A: 

array.sort does a lexicographic sort by default, for a numeric sort, provide your own function. Here's a simple example:

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

numArray.sort(compareNumbers);

Also note that sort works "in place", there's no need for the assignment.

Paul Dixon
A: 

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):

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

numArray = numArray.sort(sortNumber);
Peter