Numeric array sort in Javascript

July 3, 2006

(This is a response to Hakan Bilgin’s post Javascript Array: Sorting on his blog challenger)

Hakan presents a function for sorting a javascript array numerically, as opposed to alphabetically ([1,2,3,21].sort() => [1,2,21,3]) Such functions have existed about as long as people have needed to sort javascript arrays. However hakan’s function introduces two new features, namely the ability to choose sort order, (Which btw is defaulted to descending order in his function) and that it takes care of non-numerical objects, such as strings, in the array, and puts them in the higher end of the sorted array.

One thing I don’t like about his implementation is that it doesn’t work well with decimal numbers. ([1,2.4,2].sort_int(1) => [1,2.4,2]) 2.4 is simply rounded to 2 by parseInt and will not be guaranteed to end up on the right side of 2. But of course, sort_int was not meant to be used this way.

Anyway, I propose this code to the job:

Array.prototype.numsort=function(d){
    var d = d || -1;

    return this.sort(function(a,b){
        if (isNaN(a-b))
            return (isNaN(a)?1:-1)*d;

    return (a-b)*d;
    });
}

// Test the code
alert([1, 12, "a", 3, 29, 34, 4, 4.5, 4, 6, 46].
    numsort(-1));

I guess that’s it. If there’s anything fundamentally wrong with this code, please let me know. 🙂

Leave a comment