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 - ...
tungnt620.com1 min read
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' } ];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}`); });employees.sort((a, b) => b.age - a.age); employees.forEach((e) => { console.log(`${e.firstName} ${e.lastName} ${e.age}`); });