To sort an array of objects in TypeScript by a specific property, you can use the sort()
function and pass it a comparator function that compares the values of that property.
Here's an example code:
index.ts291 chars19 lines
In this example, we define an array of Person
objects and a compareByAge()
function that returns the difference between the ages of two Person
objects. Then we call the sort()
function on the people
array and pass it the compareByAge
function as an argument.
When we run this code, the people
array will be sorted by age in ascending order. If you want to sort in descending order, you can swap the positions of a
and b
inside the compareByAge
function.
gistlibby LogSnag