Sort numbers in Javascript array

Numbers
Sorting an array in Javascript is a snap.
You create an array and then call sort() method on that array. The Javascript sort() method sorts an array in lexicographical order. This method is very useful in sorting alphanumeric values of an array. However, sort() will not work if the array consists of numeric values. Because the alphabetical order of numbers is different from their numeric order the sorted array may not be in the order you are expecting. For example, in a dictionary sort the number “11” would come before number “5”. This may not be the result that you are looking for.
Here is an example

var ages = new Array (23,6,2,16,48,9,6);
ages.sort();

The array will become (16,2,23,48,6,6,9)

Fortunately, the work around for this problem is quite simple.
You use the same sort() method but with an additional argument. This optional argument is a reference to a comparison method that tells sort() how to compare the elements.

Here is very simple compare method. What you name your function is not important. You can call it whatever you like. The important things are the two arguments and the return statement.

function compare(a,b){
return a-b;
}

Example:
var ages = new Array (23,6,2,16,48,9,6);
ages.sort(compare);

Result: (2,6,6,9,16,23,48).

So how does it all work? There is no magic trick here. When you provide your comparison method to sort() you control how the elements are compared. If your compare(a,b) method returns

  • a positive value (a number greater than 0) ‘a’ will be put before ‘b’.
  • a negative value (a number greater than 0) ‘b’ will be put before ‘a’.
  • 0 (meaning ‘a’ and ‘b’ are equal) then the positions of these two elements will not change in the sorted array.

This array is sorted in ascending order. If you want to sort in descending order use following method
function compare(a,b){
return b-a;
}

Hope this helps.

Comments 8

  • Fastest way to sort numbers in javascript.
    Here’s my code.

    function insertionSort3 (sortMe){
    var Len = sortMe.length, i = -1, j, tmp;

    while( Len-- ){
    tmp = sortMe[++i];
    j = i;
    while( j-- && sortMe[j] > tmp ) {
    sortMe[j+1]=sortMe[j];
    }
    sortMe[j+1]=tmp;
    }
    }

    Here’s a test. You need to use Firefox and Firebug to see the results.

    var arr = [];

    var getArrOfRandomNumbers = function( howMany, largestValue ){
    var arr = [];
    howMany = ( howMany > 0 ) ? howMany : 0;
    while( howMany-- ){
    arr.push( Math.floor( Math.random() * largestValue ));
    }
    return arr;
    };

    arr = getArrOfRandomNumbers( 1000, 110 );

    console.time( "insertionSort" );
    insertionSort3( arr );
    console.timeEnd( "insertionSort" );

    arr = getArrOfRandomNumbers( 1000, 110 );

    console.time( "arr.sort()" );
    arr = arr.sort( function(a,b){return a-b;});
    console.timeEnd( "arr.sort()" );


    -Larry Battle

  • I believe this post is incorrect. The explanation above should read…

    – for a positive value (a number greater than 0), ‘b’ will be put before ‘a’.
    – for a negative value (a number less than 0), ‘a’ will be put before ‘b’.
    – for 0 (meaning ‘a’ and ‘b’ are equal), then the positions of these two elements will not change in the sorted array

    ZQ

  • […] Google is your friend second thing I found when I searched sorting numbers in javascript was this: Sort numbers in Javascript array […]

  • Thank you…was a big help…

  • kpo_attendance

  • This is really interesting, You are an excessively skilled blogger.
    I have joined your rss feed and look ahead
    to looking for more of your excellent post. Also, I have shared your website in my social networks

  • Thanks a lot!!!!

Leave a Reply

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