Sorting an array of Objects in JavaScript

If you have an array in JavaScript that doesn’t contain just simple numeric or string values, but objects with properties instead:

var employees=[];
employees[0] = {name:"Petar", age:32};
employees[1] = {name:"Nikola", age:17};
employees[2] = {name:"Milutin", age:58};
employees[3] = {name:"Slavisa", age:62};

The employees array above is an array of objects with properties of different data types, string and numeric. 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 or age. 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 sort 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 “Nikola”, employee[1] is “Petar” 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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s