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]
Written by David Morrow
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#