sort objects in typescript

To sort objects in TypeScript, you can use the sort function provided by JavaScript. However, in order to use it, you need to define a comparison function that takes two objects as parameters and returns a number indicating the order between them (-1 if the first is smaller, 0 if they are equal, 1 if the second is smaller).

Here's an example that sorts an array of objects by a "name" property, in ascending order:

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

const people: Person[] = [
  { name: "John", age: 30 },
  { name: "Alice", age: 25 },
  { name: "Bob", age: 40 }
];

people.sort((a, b) => {
  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
});

console.log(people); // [{ name: "Alice", age: 25 }, { name: "Bob", age: 40 }, { name: "John", age: 30 }]
384 chars
19 lines

In this example, we define a Person interface with two properties, "name" and "age". We then create an array of objects of this type, and sort it using the sort function. The comparison function compares the "name" property of each object, and returns -1, 0, or 1 depending on the order between them.

You can modify the comparison function to sort by a different property or in a different order.

related categories

gistlibby LogSnag