how to use the sortby function from the underscore library in javascript

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.tsx
const _ = require('underscore');

let people = [
    { name: 'John', age: 24 },
    { name: 'Jane', age: 22 },
    { name: 'Harry', age: 30 },
    { name: 'Bob', age: 28 }
];

let sortedPeople = _.sortBy(people, function(person) {
    return person.age;
});

console.log(sortedPeople);
286 chars
15 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:

[    
   { name: 'Jane', age: 22 },
   { name: 'John', age: 24 },
   { name: 'Bob', age: 28 },
   { name: 'Harry', age: 30 }
]
127 chars
7 lines

Here, the people array is sorted by age in ascending order, from youngest to oldest.

gistlibby LogSnag