Sunday 29 November 2009

Sorting an array of objects in javascript

How can we sort an array of objects based on some property of objects in javascript? For sorting a simple array, javascript provides a sort( ) method, but what to do when we want sorting on the basis of some property of an object.

Lets take an example. We have an employee array whose elements are objects.Every object has 2 properties: name and id. We want to sort the array by employee name.
Steps ares follows:

1. Create the array.

var emp = new Array( );

emp[0]= new Object("name","id");
emp[1]= new Object("name","id");
emp[2]= new Object("name","id");
emp[3]= new Object("name","id");


emp[0].name="Mn";
emp[1].name="Cb";
emp[2].name="Cd";
emp[3].name="Ab";

emp[0].id="1";
emp[1].id="2";
emp[2].id="3";
emp[3].id="4";



2. Write a function which and takes 2 employee objects as parameters compares the names of employees and returns 1,0 or -1 after comparison.

function compareNames(obj1,obj2)
{
if (obj1.name < obj2.name) { return -1; }
else if (obj1.name > obj2.name) { return 1; }
else return 0;
}


3. Call the javascript sort() function on emp array, with above function name as argument.

emp.sort(compareNames);

sort() function internally calls compareNames() and sorts the array by employee names in ascending order.
To sort in descending order, change the compareNames() as follows:


function compareNames(obj1,obj2)
{
if (obj1.name < obj2.name) { return 1; }
else if (obj1.name > obj2.name) { return -1; }
else return 0;
}

We do not need to bother how the sorting is done by sort(). To know how the objects are passed to compareNames(), put an alert() inside this function.