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.ts386 chars21 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