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.ts364 chars17 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