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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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

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

This will give you the following output:

1
2
3
4
5
[
  {name: 'Jack', surname: 'Bennington', age: 35},
  {name: 'John', surname: 'Doe', age: 21},
  {name: 'Jane', surname: 'Doe', age: 19}
]

Option 2 – Sort by age

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

This will give you the following output:

1
2
3
4
5
[
  {name: 'Jane', surname: 'Doe', age: 19},
  {name: 'John', surname: 'Doe', age: 21},
  {name: 'Jack', surname: 'Bennington', age: 35}
]