How to Sort an Array of Objects by Property in Javascript

0 min read 163 words

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}
]
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags