Last Updated: February 25, 2016
·
825
· david morrow

Javascript sort defaults to string

Javascript Array's sort() function sorts everything as a string even if they are numeric. This can be really annoying. Consider the following.

var arr = [0, 3, 5, 7, 8, 10, 2, 1];
arr.sort();
// => [0, 1, 10, 2, 3, 5, 7, 8]

Pretty obnoxious right?
If you need to sort numerically, you have to pass in a custom function to compare like the following.

var arr = [0, 3, 5, 7, 8, 10, 2, 1];
arr.sort(function (a, b) {
  return a - b;
});
// =>  [0, 1, 2, 3, 5, 7, 8, 10]