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

How to use Lodash orderby with a custom function?

1个答案

1

When using Lodash's _.orderBy function, we can achieve more complex sorting logic by passing custom iteratees. _.orderBy accepts three parameters: a collection (array or object), an iteratee, and a sort order.

Here is a concrete example demonstrating how to use custom functions for sorting:

Suppose we have a set of employee data that needs to be sorted by age and name. First, sort by age in ascending order; if ages are identical, sort by name in descending alphabetical order.

Employee data is as follows:

javascript
const employees = [ { name: 'John', age: 25 }, { name: 'Sarah', age: 25 }, { name: 'Alice', age: 30 }, { name: 'Bob', age: 22 } ];

We will use Lodash's _.orderBy method with custom functions to handle this composite sorting:

javascript
import _ from 'lodash'; const sortedEmployees = _.orderBy( employees, [ 'age', // First sorting criterion is age (employee) => employee.name // Second sorting criterion is name ], ['asc', 'desc'] // Specify sort order for each criterion ); console.log(sortedEmployees);

The output will be:

javascript
[ { name: 'Bob', age: 22 }, { name: 'Sarah', age: 25 }, { name: 'John', age: 25 }, { name: 'Alice', age: 30 } ]

In this example, Bob appears first because he is the youngest. Sarah and John have the same age, but since we specified descending alphabetical order for names, Sarah precedes John. Alice, being the oldest, appears last.

This approach is highly flexible and can be adjusted according to specific requirements to modify sorting criteria and order, making it ideal for handling complex data sorting scenarios.

2024年8月24日 01:40 回复

你的答案