sort array of objects by property in typescript

To sort an array of objects in TypeScript by a specific property, you can use the sort() function and pass it a comparator function that compares the values of that property.

Here's an example code:

index.ts
interface Person {
  name: string;
  age: number;
}

const people: Person[] = [
  { name: 'John', age: 28 },
  { name: 'Jane', age: 25 },
  { name: 'Bob', age: 32 }
];

function compareByAge(a: Person, b: Person) {
  return a.age - b.age;
}

people.sort(compareByAge);

console.log(people);
291 chars
19 lines

In this example, we define an array of Person objects and a compareByAge() function that returns the difference between the ages of two Person objects. Then we call the sort() function on the people array and pass it the compareByAge function as an argument.

When we run this code, the people array will be sorted by age in ascending order. If you want to sort in descending order, you can swap the positions of a and b inside the compareByAge function.

gistlibby LogSnag