EN
JavaScript - sort array of objects by multiple properties
0
points
In this article, we would like to show you how to sort array of objects by multiple properties using JavaScript.
Quick solution:
array.sort(function(a, b) {
return a.property1.localeCompare(b.property1) || a.property2 - b.property2;
});
Practical example
In this example, we sort an array of objects by name
and age
properties using the custom compare function as an argument of the sort()
method.
// ONLINE-RUNNER:browser;
var users = [
{ name: 'Ann', age: 28 },
{ name: 'Chris', age: 29 },
{ name: 'Tom', age: 26 },
{ name: 'Ann', age: 25 },
{ name: 'Chris', age: 26 },
];
users.sort(function(a, b) {
return a.name.localeCompare(b.name) || a.age - b.age;
});
console.log(JSON.stringify(users, null, 4));
2. Reverse order
To reverse the order, simply swap arguments places after the return
statement.
// ONLINE-RUNNER:browser;
var users = [
{ name: 'Ann', age: 28 },
{ name: 'Chris', age: 29 },
{ name: 'Tom', age: 26 },
{ name: 'Ann', age: 25 },
{ name: 'Chris', age: 26 },
];
users.sort(function (a, b) {
return b.name.localeCompare(a.name) || b.age - a.age;
});
console.log(JSON.stringify(users, null, 4));