Languages
[Edit]
EN

JavaScript - sort array of objects by multiple properties

0 points
Created by:
Zoya-Gaines
653

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));

References

  1. Array.prototype.sort() - JavaScript | MDN

Alternative titles

  1. JavaScript - sort array of objects by multiple fields
  2. JavaScript - sort array of objects by two properties
  3. JavaScript - use sort function to sort by first then by second
  4. JavaScript - sort array of objects alphabetically and then numerically
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join