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 ]
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 ]
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 yield negative(-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 yield 0 meaning they are equal
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.
Default sort order is alphabetic and ascending. If you want to sort the number you could do something like this:
function sortNumber(a,b) {
return a - b;
}
var numArray = [140000, 104, 99];
numArray.sort(sortNumber);
You may try:
[5, 10, 1].sort(function(a, b){ return a - b }) # print [1, 5, 10]
you can try
[5, 10, 1].sort(function(a,b){return a-b})