sort an array of objects in javascript

To sort an array of objects in JavaScript, you can use the sort() method of the array object along with a compare function as an argument.

The compare function takes two parameters, which are the two objects being compared. It should return a negative value if the first object should come before the second object, a positive value if the second object should come before the first object, and 0 if they are equal.

Here is an example of how to sort an array of objects by a property named age:

index.tsx
const people = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Bob', age: 35 }
];

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

console.log(people); // Output: [{ name: 'Jane', age: 25 }, { name: 'John', age: 30 }, { name: 'Bob', age: 35 }]
258 chars
10 lines

In this example, we use an arrow function to compare the objects by their age property. The sort() method modifies the original array, so people is now sorted by age in ascending order.

gistlibby LogSnag