How to arithmetically sort an array in Javascript

Something interesting that I discovered tonight is that JavaScript’s sort() function by default sorts values lexicographically (that means, for example, that “10″ comes before “2″), even when the array contains numerical data.

Let’s consider the following code:

var values = [ 1, 10, 100, 4, 20, 3 ];
values.sort();
console.log(values);

The above code yields:

[1, 10, 100, 20, 3, 4]

However, in case we need to sort those values as numbers, it is possible to pass a “comparator” function as an argument to sort(), and this function will be used by sort() to decide the order of the elements. To sort arithmetically the array in the above example, we will have to do it like this:

var values = [ 1, 10, 100, 4, 20, 3 ];
values.sort( function(a,b) {
    return a-b;
});
console.log(values);

Now the code above yields:

[1, 3, 4, 10, 20, 100]

For reverse sorting we just have to swap the two operands in the sorting function:

var values = [ 1, 10, 100, 4, 20, 3 ];
values.sort( function(a,b) {
    return b-a;
});
console.log(values);

Result:

[100, 20, 10, 4, 3, 1]

One thing to notice is that above code even works if the values are stored as strings; that’s because the values of the operands are implicitly converted to integers by the subtraction operator (‘-’):

var values = [ '1', '10', '100', '4', '20', '3' ];
values.sort( function(a,b) {
    return a-b;
});
console.log(values); 

Result:

["1", "3", "4", "10", "20", "100"]

If we would prefer to be more “bullet-proof” when dealing with numbers stored as strings, we could use the parseInt() function to make sure we are really dealing with integer values.

var values = [ '1', '10', '100', '4', '20', '3' ];
values.sort( function(a,b) {
    return parseInt(a)-parseInt(b);
});
console.log(values);

Result:

["1", "3", "4", "10", "20", "100"]

Notice that the sorted values remained stored as strings.

So, that was pretty much all of it, I hope this helped! :-)

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>