Sort array of object in javascript

Problem: sort array of objects by a property

Example:

const array = [
  { id: 1, name: "tung" },
  { id: 3, name: "nguyen" },
  { id: 2, name: "thanh" }
]

Solution:

// Sort list array by id
const sortedArray = array.sort((item1, item2) => item1.id - item2.id)

Explain: Array in javascript has a sort method to sort. sort method have input is a compare function with two items and output is:

  • a positive number means item1 will place before item2
  • a negative number means item1 will place after item2
  • a zero number mean no change in the order of items

Comments (2)

Purvi Barot's photo

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