Blog

Sort Function in JavaScript Arrays

The sort function in JavaScript Arrays allows performs sorting of array elements. Like all of JavaScript this function is remarkably flexible as well.
Let us say we want to sort an array.
var a=Array(4,5,3,-2);
To sort you call a.sort();
This will sort the array numerically.
-2,3,4,5

To change the sorting mode we can define a function and pass it as a parameter to the JavaScript sort function that actually does the comparing.
The function is defined this way:
function(a,b)
It should have two parameters. It should return a negative number if a<b,0 if a=b, and positive number if a>b
This is sufficient:
function(x,y)
{
return a-b;
}
will work.

The sort function with a function parameter is called this way:

var a=new Array(4,5,-6,-7,2);
var f=function(x,y)
{
return a-b;
}

Call it his way:
a.sort(f);

To sort in reverse we can write:

var a=new Array(4,5,-6,-7,2);
var f=function(x,y)
{
return b-a;
}
a.sort(f);

Try some options on functions in this page:
http://blogs.computer-programmers.in/samples/arraysorting.html