Sort numbers in Javascript array
Dec 05
Javascript Array, Javascript, numeric array, Sort, Sort numbers, sort numeric arrays 4 Comments

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.
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.
Related posts:



Oct 02, 2008 @ 21:48:36
whoa thanks! bighelp!
Oct 10, 2010 @ 14:28:14
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
Dec 21, 2010 @ 16:27:41
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