Nov

24

JavaScript Sort Double Digits

November 24, 2008 |

JavaScript has a built-in sorting method: Array#sort. It’s great to have a built-in method like this but when we sort the following array:
var a = [2, 5, 4, 8, 9, 1, 3, 10, 7, 6].sort();
alert(a);

guess what would you get?

[1, 10, 2, 3, 4, 5, 6, 7, 8, 9]

oops! 10 is smaller than 2! As it happens, sort is called with no arguments will coerce the array items into strings before it compares them.

So what if we want to compare the numbers directly? Then we must pass a function argument into sort:

[2, 5, 4, 8, 9, 1, 3, 10, 7, 6].sort(function(a, b) {
return a – b;
});

Now we will get:


[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If you got the same problem, hope this helps! :)



Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

Sponsors




Links