Skip to content Skip to sidebar Skip to footer

Why Can't Javascript Sort [5, 10, 1]?

This seems like a simple sort, yet JavaScript is giving an incorrect result. Am I doing something wrong or is this a language quirk? [5, 10, 1].sort(); [ 1, 10, 5 ]

Solution 1:

Javascript sorts alphabetically. This means that "10" is lower than "5", because "1" is lower than "5".

To sort numerical values you need to pass in numerical comparator like this:

function sorter(a, b) {
  if (a < b) return -1;  // any negative number works
  if (a > b) return 1;   // any positive number works
  return 0; // equal values MUST yield zero
}

[1,10, 5].sort(sorter);

Or you can cheat by passing simpler function:

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

[1, 10, 5].sort(sorter);

Logic behind this shorter function is that comparator must return x>0 if a > b, x<0 if a < b and zero if a is equal to b. So in case you have

a=1 b=5
a-b will yieldnegative(-4) number meaning b is larger than a

a=5 b=1
a-b will yield positive number(4) meaning a is larger than b

a=3 b=3
a-b will yield0 meaning they are equal

Solution 2:

You have to pass a function to the sort method.

var points = [5, 10, 1];
points.sort(function(a,b){return a-b});

Here is a working fiddle.

Solution 3:

Default sort order is alphabetic and ascending. If you want to sort the number you could do something like this:

functionsortNumber(a,b) {
    return a - b;
}

var numArray = [140000, 104, 99];
numArray.sort(sortNumber);

Solution 4:

function sortit(a, b){ return (a-b); }
[1, 5, 10].sort(sortit);

Solution 5:

You may try:

[5, 10, 1].sort(function(a, b){ return a - b })   # print [1, 5, 10]

Post a Comment for "Why Can't Javascript Sort [5, 10, 1]?"