Last Updated: February 25, 2016
·
1.221K
· 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]

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside