To sort an array of objects in JavaScript, you need to have a compareFunction that compares the objects and determines their order. You can use the Array.sort()
method to sort the array.
Here's an example of sorting an array of objects by a particular property:
index.tsx289 chars13 lines
In the first example, we sort the array by the name
property in ascending order. The compareFunction
takes two parameters a
and b
which represent two objects being compared. The function compares the name
property of both a
and b
and returns 1
if a.name
is greater than b.name
, and -1
if it is smaller. This sorts the array in ascending order based on the name
property.
In the second example, we sort the array by the age
property in descending order. The compareFunction
subtracts b.age
from a.age
, which returns a negative number if a.age
is less than b.age
, and a positive number if a.age
is greater. This sorts the array in descending order based on the age
property.
gistlibby LogSnag