Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Sorting an array of objects

Taking things one step further, lets say your array doesn't contain just simple numeric or string values, but objects with properties instead:

var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}

The employees array above is an array of objects with properties of different data types, from string, numeric, to a date string. The sort() method can be used to sort the array based on the values of one of these properties, such as sorting the array by name, age, or even when they retire. The basic idea is to modify the compare function so it compares the desired properties' values. Lets see how this works now.

- Sort by employee age

Lets start by sorting the employees array by their ages (ascending). Here's the comparison function that does this:

employees.sort(function(a, b){
 return a.age-b.age
})

With the above sort method, the employees array is now sorted by the age property, so employee[0] is "Edward", employee[1] is "George" etc. The process is very similar to sorting an array with numeric values (ascending), except instead of subtracting b from a, we need to subtract b.age from a.age instead, or the array element's property we wish to base the sorting on.

- Sort by employee name

Sorting by employee age may be seen as a little insensitive in this day and age, so lets go by employee names instead (ascending). Recall that by default, to sort an array containing primitive values (such as strings) alphabetically, you would simply call the sort() method without any comparison function passed in directly on the array, such as myarray.sort(). This doesn't work however when the data we wish to sort using is deep inside a property of the array object, and not the array itself. So what to do? Well, the trick is just to manually define the comparison function that sorts an array alphabetically, which in turn allows us to specify where this string data is located. Take a look at the following:

employees.sort(function(a, b){
 var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
 if (nameA < nameB) //sort string ascending
  return -1
 if (nameA > nameB)
  return 1
 return 0 //default return value (no sorting)

})

This will sort the employees array by the name property ascending, so employee[0] is "Christine", employee[1] is "Edward" and so on. Here we are comparing two strings a.name to b.name and returning either -1, 1, or 0 accordingly to sort, exactly the formula used inexplicitly by the sort() method without any function passed in. And as you might have just discovered, in JavaScript you can certainly compare two string (done so alphabetically).

- Sort by date (retirement date)

Finally, lets say you wish to sort the employees based on each employee's date of retirement. This information is stored in the "retiredate" property, though to make things more interesting, not as a date object, but a string representing a date. What we'll have to do first then is create a valid date object out of this string first, though afterwards, the process is the same as sorting by numbers:

employees.sort(function(a, b){
 var dateA=new Date(a.retiredate), dateB=new Date(b.retiredate)
 return dateA-dateB //sort by date ascending

})

This sorts the array so the earliest to retire employees appear first (employees[0] equals "Sarah"). It works because JavaScript lets you compare and/or do arithmetic on date objects, which are automatically converted to numeric representations first.

To wrap up this tutorial, lets see a full blown example of using sort() to create a numbers and word sorter!

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.