Javascript Sorting an Array of Objects  Hot PDF Print E-mail
Tag it:
Delicious
Furl it!
Digg
NewsVine
Reddit
YahooMyWeb
Technorati
Articles Reviews Javascript
Written by Larry Gomez   
Friday, 09 March 2007

If you want to sort an array of objects based on the value of one of the properties of the objects can use the next solution:

Define a comparison function as usual, but let the actual comparisons work on the properties of the objects being passed to the function two at a time.


We'll start with the array of sales objects:

var sales = new Array( );
sales[sales.length] = {period:"q1", region:"east", total:2300};
sales[sales.length] = {period:"q2", region:"east", total:3105};
...
sales[sales.length] = {period:"q4", region"west", total:3810};

If you want to sort the sales array in descending order of the values of the total properties of each object, define a comparison function that returns the appropriate values based on the arithmetic:

function compareTotals(a, b) {
return b.total - a.total;
}

Because each array entry passed as parameters a and b is an object, you can use those parameter variables to reference the properties of the objects as they pass through in waves during the full sort operation.

To sort the array by way of the comparison function, pass the function's reference to the sort( ) method of the array:

sales.sort(compareTotals);

Recall that the sort( ) method modifies the order of the original array. But you can invoke other sort( ) methods (that call other comparison functions) to resort the array by other criteria.

Comparison functions can get rather elaborate if necessary. It all depends on the kind of data in your object properties and what kind of sorting you need to perform.

For example, if an object is defined with separate properties for month, day, and year, and if you want to sort the objects by the dates that those numbers represent, the comparison function can create date objects from those values and then compare the resulting date objects:

function compareDates(a, b) {
var dateA = new Date(a.year, a.month, a.date);
var dateB = new Date(b.year, b.month, b.date);
return dateA - dateB;
}

If sorting is required of string values in properties, you have to be more explicit in the comparisons you perform and the values you return. You may also want to eliminate case as a factor by comparing values converted to all upper- or all lowercase characters. The following function sorts string values of the lastName property of an array of objects:

function compareNames(a, b) {
var nameA = a.lastName.toLowerCase( );
var nameB = b.lastName.toLowerCase( );
if (nameA < nameB) {return -1}
if (nameA > nameB) {return 1}
return 0;
}

Because the toLowerCase( ) method of a string doesn't disturb the case of the original string, the object values are ready to be displayed as entered into the data structure.


User reviews

Average user rating from: 7 user(s)

Overall rating
5.0
 

Add new review



1 of 1 people found the following review helpful

Beautiful!!!, Wednesday, 02 November 2011

Written by Yuriy

Overall rating
5.0
Used it to sort IFRAMES :) http://codecorner.galanter.net/2011/11/02/how-to-load-iframes-in-order-according-to-priority/
Was this review helpful to you? yes     no

1 of 1 people found the following review helpful

Sort Function, Wednesday, 05 October 2011

Written by Scott

Overall rating
5.0
Worked great! Thank you!

function compareNames(a, b) {
var nameA = a.lastName.toLowerCase( );
var nameB = b.lastName.toLowerCase( );
if (nameA nameB) {return 1}
return 0;
}
Was this review helpful to you? yes     no

1 of 4 people found the following review helpful

OMG! Thank you!, Friday, 12 August 2011

Written by Peter

Overall rating
5.0
data.sort( function(a, b) {return b.count - a.count} );

Worked like a charm!
Was this review helpful to you? yes     no

0 of 1 people found the following review helpful

blew me away...., Thursday, 28 April 2011

Written by thomas

Overall rating
5.0
I've been searching for an easy sort of an array of objects and this is a great one.
Was this review helpful to you? yes     no

0 of 0 people found the following review helpful

So simple and clean!, Tuesday, 08 February 2011

Written by Bill

Overall rating
5.0
Thanks a lot for this. Works like a charm and is very clean and fast. Great work!
Was this review helpful to you? yes     no

4 of 10 people found the following review helpful

Simple Understanding, Monday, 01 February 2010

Written by Nanda Kumar

Overall rating
5.0
Simple Understanding!
fast understanding example that has been provided.

can u explain the concept for
return b.total - a.total;
here how substract is taking place..

thankx in advance,
Nanda
Was this review helpful to you? yes     no

13 of 16 people found the following review helpful

Very Nice, Have long been thinking about that one, Thursday, 29 January 2009

Written by Nils Daniel Wittwer

Overall rating
5.0
Thanks you so much, I have long thought how to sort an Object list in Javascript. In PHP it's so easy with real associative arrays. I even got to the point where I implemented my own bubble sort algorithm. This is so much nicer!
Thx!
Was this review helpful to you? yes     no


Powered by jReviews

Last Updated ( Tuesday, 28 June 2011 )
 
< Prev   Next >