The sortBy
function from the Underscore library in Javascript allows you to sort an array based on a particular attribute or property. It takes in two arguments: the first one is the array to be sorted, and the second argument is an iterator function that tells the function what to sort the array by.
Here's an example usage of sortBy
function:
index.tsx286 chars15 lines
In this example, we have an array of people with their respective ages. We want to sort this array by age, so we call the sortBy
function and pass in the people
array as the first argument. As the second argument, we create an iterator function that returns the value of the age
property for each person object.
The sortBy
function then sorts the people
array based on their age
property, and returns a new, sorted array. We assign this new array to the sortedPeople
variable and print it to the console.
The output of this code would be:
127 chars7 lines
Here, the people
array is sorted by age in ascending order, from youngest to oldest.
gistlibby LogSnag