Javascript Sorts Arrays Badly!

By Keith Connolly on December 10, 2012

Get Reading

There comes a time in a coders life that s/he must sort an array numericly.  When this time comes s/he comes to realize that, yes, Javascript does crappy array sorting!  

Take for example this code:

var arr = [4,3,2,1,0,10];
arr.sort();
// Here's what it looks like! [0,1,10,2,3,4]

Not great, right?

All you need to do is pass this anonymous function in your sort.

arr.sort(function(a,b){return a-b});
//or if you want the order reversed...
arr.sort(function(a,b){return b-a});
 
Basically you need to pass a function that returns -1, 0, or 1 for the comparison.  This method does just that.  

Get in touch

I really like hearing from those who read my content, engauge with me via the comments on each post are by one of the many contact methods below.


Keith Connolly
Queen Creek, Arizona 85142
P: (480) 231-9285