Sort Array of Objects by Property Values in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial shows how to sort array in of objects by their property values. In JavaScript, we can achieve this by using sort() method.

Example

const employees = [
  { name: "Jack", age: 54 },
  { name: "Liam", age: 16 },
  { name: 'Noah', age: 43 }
];

//* sort by name of employees ascending
employees.sort((a, b) => (a.name > b.name) ? 1 : -1);
console.log("Sort by name [ASC]=",employees);

//* sort by age of employees descending
employees.sort((a,b) => (a.age > b.age) ? -1 : 1);
console.log("Sort by age [DESC]=",employees);

 The sort() method of Array, takes as parameters 2 objects contained in the array a and b . When we return 1, the function takes the object b and places it in precedence order, sorting b over the object a. Returning -1 would do the opposite.

Output
Sort by name [ASC]= [
  { name: 'Jack', age: 54 },
  { name: 'Liam', age: 16 },
  { name: 'Noah', age: 43 }
]
Sort by age [DESC]= [
  { name: 'Jack', age: 54 },
  { name: 'Noah', age: 43 },
  { name: 'Liam', age: 16 }
]