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