Posts Tagged sorting

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



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 ( < { return -1; }
else if ( > { return 1; }
else return 0;

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


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 ( < { return 1; }
else if ( > { 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.


Leave a comment