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

How to Sort items in an array by more than one field with lodash

4 个月前提问
3 个月前修改
浏览次数24

1个答案

1

在使用 lodash 来按多个字段对数组进行排序时,可以使用 _.orderBy 函数。这个函数允许你指定排序的字段和每个字段的排序顺序(升序或降序)。下面我将通过一个具体的例子来展示如何使用这个方法。

假设我们有一个代表人员的数组,每个人员对象包含姓名、年龄和入职年份,我们需要先按照年龄升序排列,如果年龄相同,则按入职年份降序排列。

首先,你需要引入 lodash 库:

javascript
const _ = require('lodash');

然后,假设我们有以下数组:

javascript
let employees = [ { name: "John Doe", age: 25, hireYear: 2017 }, { name: "Jane Smith", age: 25, hireYear: 2015 }, { name: "Alicia Keys", age: 30, hireYear: 2010 }, { name: "James Brown", age: 30, hireYear: 2012 } ];

使用 _.orderBy 函数对这个数组进行排序:

javascript
let sortedEmployees = _.orderBy(employees, ['age', 'hireYear'], ['asc', 'desc']);

在这个例子中,['age', 'hireYear'] 指定了排序的顺序是先按 age 升序排列,如果 age 相同,则按照 hireYear 降序排列。对应的,['asc', 'desc'] 分别指定了对应字段的排序方式。

打印排序后的结果:

javascript
console.log(sortedEmployees);

这将输出:

json
[ { "name": "Jane Smith", "age": 25, "hireYear": 2015 }, { "name": "John Doe", "age": 25, "hireYear": 2017 }, { "name": "James Brown", "age": 30, "hireYear": 2012 }, { "name": "Alicia Keys", "age": 30, "hireYear": 2010 } ]

从输出可以看出,数组首先按年龄升序排列,在年龄相同的情况下,按入职年份降序排列。这就是如何使用 lodash 的 _.orderBy 方法按多个字段对数组进行排序的一个实例。

2024年6月29日 12:07 回复

你的答案