sort array of objects by either or in javascript

To sort an array of objects in JavaScript, you need to have a compareFunction that compares the objects and determines their order. You can use the Array.sort() method to sort the array.

Here's an example of sorting an array of objects by a particular property:

index.tsx
const array = [
  {name: 'John', age: 25},
  {name: 'Emily', age: 35},
  {name: 'Steve', age: 18},
  {name: 'Bob', age: 32},
];

// Sort by name in ascending order
array.sort((a, b) => (a.name > b.name) ? 1 : -1);

// Sort by age in descending order
array.sort((a, b) => (b.age - a.age));
289 chars
13 lines

In the first example, we sort the array by the name property in ascending order. The compareFunction takes two parameters a and b which represent two objects being compared. The function compares the name property of both a and b and returns 1 if a.name is greater than b.name, and -1 if it is smaller. This sorts the array in ascending order based on the name property.

In the second example, we sort the array by the age property in descending order. The compareFunction subtracts b.age from a.age, which returns a negative number if a.age is less than b.age, and a positive number if a.age is greater. This sorts the array in descending order based on the age property.

gistlibby LogSnag