Sort numbers in Javascript array

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);

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;

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

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.