乐闻世界logo
搜索文章和话题

How to import and use _.sortBy from lodash

1个答案

1

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:

bash
npm install lodash

or

bash
yarn 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:

javascript
import 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:

javascript
const people = [ { name: 'John', age: 48 }, { name: 'Jane', age: 32 }, { name: 'Michael', age: 40 }, { name: 'Karen', age: 24 } ];

Using _.sortBy, you can write:

javascript
const 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:

javascript
const sortedPeople = sortBy(people, ['age', 'name']);
2024年7月18日 22:29 回复

你的答案