JavaScript(JS) JS sort array of objects by property values

www.‮i‬giftidea.com

To sort an array of objects by a specific property value in JavaScript/JS, you can use the sort() method along with a comparison function. Here's an example:

const myArray = [
  { name: "John", age: 25 },
  { name: "Jane", age: 30 },
  { name: "Bob", age: 20 }
];

// Sort by name
myArray.sort((a, b) => (a.name > b.name) ? 1 : -1);
console.log(myArray);

// Sort by age
myArray.sort((a, b) => (a.age > b.age) ? 1 : -1);
console.log(myArray);

In this example, we have an array of objects with two properties: name and age. To sort by name, we use the comparison function (a, b) => (a.name > b.name) ? 1 : -1. This function takes two arguments, a and b, which represent two objects being compared. The function returns 1 if a should come after b in the sorted array, -1 if a should come before b, and 0 if they are equal. In this case, we compare the name property of each object using the greater than operator, which returns a boolean. If a.name is greater than b.name, we return 1, otherwise we return -1.

Similarly, to sort by age, we use the comparison function (a, b) => (a.age > b.age) ? 1 : -1. This time we compare the age property of each object.

After sorting, we log the sorted array to the console using console.log(myArray).