sort an array of objects with known keys in typescript

To sort an array of objects with known keys in TypeScript, you can use the array.sort() method and pass in a custom comparison function that compares the values of a specific key in the objects.

Here's an example:

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

const people: Person[] = [
  { name: "Alice", age: 21 },
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 18 },
];

// sort by age in ascending order
people.sort((a, b) => a.age - b.age);

console.log(people);
// Output: [{ name: "Charlie", age: 18 }, { name: "Alice", age: 21 }, { name: "Bob", age: 25 }]
364 chars
17 lines

In this example, we have an array of Person objects with name and age properties. To sort the array by age in ascending order, we pass in a comparison function that subtracts the age of the second object from the age of the first object (a.age - b.age). This function will return a negative number if a is younger than b, a positive number if a is older than b, and zero if they are the same age. The sort method will then use this comparison function to sort the array in ascending order based on the age property.

gistlibby LogSnag