sort an array of objects by a specific property in typescript

To sort an array of objects by a specific property in TypeScript, you can use the Array's built-in sort method.

Here's an example code snippet:

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

const myArray: MyObject[] = [
  { id: 1, name: "John", age: 25 },
  { id: 2, name: "Jane", age: 30 },
  { id: 3, name: "Bob", age: 20 }
];

// Sort by id
myArray.sort((a, b) => a.id - b.id);

// Sort by name
myArray.sort((a, b) => a.name.localeCompare(b.name));

// Sort by age
myArray.sort((a, b) => a.age - b.age);
386 chars
21 lines

In the sort method, we pass a callback function that takes two arguments (the two objects being compared), and returns a number that represents their relative order. If the returned number is negative, it means that the first object should come before the second; if it's positive, it means that the second object should come before the first; if it's zero, it means that their order doesn't matter.

In the examples above, we're using different comparison methods depending on the property we're sorting by (numeric for id and age, and lexicographic for name).

gistlibby LogSnag