First, _.sortBy is a function from the Lodash library that sorts elements in an array. Depending on your development environment, you may need to install Lodash first. If you're using Node.js, you can install it using npm or yarn:
bashnpm install lodash
or
bashyarn add lodash
After installation, you can import the sortBy function on demand in your JavaScript file. Lodash supports module-based imports, which allows you to import only the necessary functions, reducing the final bundle size. Here's an example of how to import only the _.sortBy function:
javascriptimport sortBy from 'lodash/sortBy';
Next, I'll demonstrate how to use _.sortBy to sort an array of objects. Assume we have the following array containing information about several people, and we want to sort them by age:
javascriptconst people = [ { name: 'John', age: 48 }, { name: 'Jane', age: 32 }, { name: 'Michael', age: 40 }, { name: 'Karen', age: 24 } ];
Using _.sortBy, you can write:
javascriptconst sortedPeople = sortBy(people, 'age');
This line of code sorts the elements in the people array based on the age property. _.sortBy defaults to ascending order. After sorting, the sortedPeople array will be:
javascript[ { name: 'Karen', age: 24 }, { name: 'Jane', age: 32 }, { name: 'Michael', age: 40 }, { name: 'John', age: 48 } ]
Additionally, if you need to sort based on multiple properties, you can pass an array of property names to _.sortBy. For example, if you also want to sort by name when ages are the same, you can do this:
javascriptconst sortedPeople = sortBy(people, ['age', 'name']);