Categories
Uncategorized

Sort javascript objects based on multiple properties

When you want to sort javascript objects based on 2 properties,  you can use the following code. In this example here we have an array of people (objects) here. I want to sort them by first name and then by their last names. So, what I do in my compare function to get the required output is to sort them by their last names, only when their first names are equal.

var people = [{
 "fname": "shiva",
 "lname": "kiran"
}, {
 "fname": "aru",
 "lname": "wind"
}, {
 "fname": "shiva",
 "lname": "charan"
}];

var compare = function(a, b) {
 var ret = a.fname.localeCompare(b.fname)
 if (ret === 0) {
 return a.lname.localeCompare(b.lname);
 }
 return ret;
};

people.sort(compare);
console.log(people);

Output

 [{
 "fname": "aru",
 "lname": "wind"
}, {
 "fname": "shiva",
 "lname": "charan"
},
{
 "fname": "shiva",
 "lname": "kiran"
}]

Demo

If you would like to use integers then, this example with ages would help. Here the people are sorted by first names and then by their ages.

var people = [{
 "fname": "shiva",
 "lname": "kiran",
 "age": 20
}, {
 "fname": "aru",
 "lname": "wind",
 "age": 21
}, {
 "fname": "shiva",
 "lname": "charan",
 "age": 19
}];

var compare = function(a, b) {
 var ret = a.fname.localeCompare(b.fname)
 if (ret === 0) {
 return a.age - b.age;
 }
 return ret;
};

people.sort(compare);
console.log(people);

Output

[{
 "fname": "aru",
 "lname": "wind"
 "age": 21
}, {
 "fname": "shiva",
 "lname": "charan"
 "age": 19
},
{
 "fname": "shiva",
 "lname": "kiran",
 "age": 20
}]

Demo

If you would like to sort objects in descending order (strings or integers), then just return the negative of the result.

var people = [{
 "fname": "shiva",
 "lname": "kiran",
 "age": 20
}, {
 "fname": "aru",
 "lname": "wind",
 "age": 21
}, {
 "fname": "shiva",
 "lname": "charan",
 "age": 19
}];

var compare = function(a, b) {
 var ret = a.fname.localeCompare(b.fname)
 if (ret === 0) {
 return b.age - a.age;
 }
 return -1*ret;
};

people.sort(compare);
console.log(people);

Output

[{
 "fname": "shiva",
 "lname": "kiran",
 "age": 20
}, 
{
 "fname": "shiva",
 "lname": "charan"
 "age": 19
},
{
 "fname": "aru",
 "lname": "wind"
 "age": 21
}] 

Demo