• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

3. Arrays and Objects > 3.11. Sorting an Array of Objects

Sorting an Array of Objects

NN 4, IE 4

Problem

You want to sort an array of objects based on the value of one of the properties of the objects.

Solution

Sorting an array of objects relies on a logical extension of the comparison function described for simple arrays in Recipe 3.5. 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.

To demonstrate the concept, 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};

PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint