Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of integers correctly

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(); 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 actually sort on integer value?

like image 455
peirix Avatar asked Jun 30 '09 10:06

peirix


People also ask

How do you sort an array in order?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.


2 Answers

Just building on all of the above answers, they can also be done in one line like this:

var numArray = [140000, 104, 99]; numArray = numArray.sort(function (a, b) {  return a - b;  });  //outputs: 99, 104, 140000 
like image 33
MarzSocks Avatar answered Sep 21 '22 04:09

MarzSocks


By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -

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.

like image 158
aks Avatar answered Sep 20 '22 04:09

aks