---
title: "Comment by Purvi Barot on \"Sort array of object in javascript\" | Hashnode"
description: "To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects. Suppose that you have an array of"
url: "https://hashnode.com/posts/sort-array-of-object-in-javascript/603e6c6fff443a0a4499df6a/comment/603f1339fb37920a1fc642ef"
---

[Discussion](https://hashnode.com/posts/sort-array-of-object-in-javascript/603e6c6fff443a0a4499df6a)

Comment [Sort array of object in javascript](https://hashnode.com/posts/sort-array-of-object-in-javascript/603e6c6fff443a0a4499df6a)

[Purvi Barot](https://hashnode.com/@purvi)

[Mar 3, 2021](https://hashnode.com/posts/sort-array-of-object-in-javascript/603e6c6fff443a0a4499df6a/comment/603f1339fb37920a1fc642ef)

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

Suppose that you have an array of employee objects as follows:

```
let employees = [
    {
        firstName: 'John',
        lastName: 'Doe',
        age: 27,
        joinedDate: 'December 15, 2017'
    },

    {
        firstName: 'Ana',
        lastName: 'Rosy',
        age: 25,
        joinedDate: 'January 15, 2019'
    },

    {
        firstName: 'Zion',
        lastName: 'Albert',
        age: 30,
        joinedDate: 'February 15, 2011'
    }
];
```

-   The following statement snippet sorts the employees array by ages in ascending order:

```
employees.sort((a, b) => {
    return a.age - b.age;
});
```

To display the employees, you use the forEach() method:

```
employees.forEach((e) => {
    console.log(`${e.firstName} ${e.lastName} ${e.age}`);
});
```

-   To sort the employees by ages in descending order, you just need to reverse the order in the comparison function. For example:

```
employees.sort((a, b) => b.age - a.age);

employees.forEach((e) => {
    console.log(`${e.firstName} ${e.lastName} ${e.age}`);
});
```

[Tung Nguyen](https://hashnode.com/@tungnt)

[Mar 3, 2021](https://hashnode.com/posts/sort-array-of-object-in-javascript/603e6c6fff443a0a4499df6a/comment/603f1339fb37920a1fc642ef#reply-603f4fa0ff443a0a4499eec6)

Thank Purvi
