To sort an array of objects in JavaScript, you can use the sort()
method of the array object along with a compare function as an argument.
The compare function takes two parameters, which are the two objects being compared. It should return a negative value if the first object should come before the second object, a positive value if the second object should come before the first object, and 0 if they are equal.
Here is an example of how to sort an array of objects by a property named age
:
index.tsx258 chars10 lines
In this example, we use an arrow function to compare the objects by their age
property. The sort()
method modifies the original array, so people
is now sorted by age in ascending order.
gistlibby LogSnag