sort by property in javascript

To sort an Array of Objects in JavaScript by one of its properties, we can use the Array.sort() method and a comparator function that compares the values of two properties of each Object. The comparator function should return a negative value if the first property is smaller than the second, a positive value if the first property is greater than the second, or zero if they are equal.

Here's an example that sorts an Array of Objects by the 'age' property in ascending order:

index.tsx
let people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 20 },
];

people.sort((a, b) => a.age - b.age);

console.log(people);
// Output: [{ name: 'Charlie', age: 20 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]
265 chars
11 lines

In this example, the Array.sort() method receives a comparator function that compares the 'age' property of each Object. If we wanted to sort the Array in descending order, we could return b.age - a.age instead.

gistlibby LogSnag