How to Sort an Array of Objects by Property in Javascript


If you need to sort an array of objects by their property values using Javascript, then you don’t need to look further than the built-in sort functionality.

Step 1 – Create an array of objects to work with

let people = [
    {
        name : "John",
        surname : "Doe",
        age : 21
    }, {
        name : "Jack",
        surname : "Bennington",
        age : 35
    }, {
        name : "Jane",
        surname : "Doe",
        age : 19
    }
];

Step 2 – Sort by keys

Option 1 – Sort by surname

people.sort((a, b) => a.surname.localeCompare(b.surname));
console.log(people);

This will give you the following output:

[
  {name: 'Jack', surname: 'Bennington', age: 35},
  {name: 'John', surname: 'Doe', age: 21},
  {name: 'Jane', surname: 'Doe', age: 19}
]

Option 2 – Sort by age

people.sort((a, b) => {
    return a.age - b.age;
});
console.log(people);

This will give you the following output:

[
  {name: 'Jane', surname: 'Doe', age: 19},
  {name: 'John', surname: 'Doe', age: 21},
  {name: 'Jack', surname: 'Bennington', age: 35}
]