在使用 lodash 来按多个字段对数组进行排序时,可以使用 _.orderBy
函数。这个函数允许你指定排序的字段和每个字段的排序顺序(升序或降序)。下面我将通过一个具体的例子来展示如何使用这个方法。
假设我们有一个代表人员的数组,每个人员对象包含姓名、年龄和入职年份,我们需要先按照年龄升序排列,如果年龄相同,则按入职年份降序排列。
首先,你需要引入 lodash 库:
javascriptconst _ = require('lodash');
然后,假设我们有以下数组:
javascriptlet 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
函数对这个数组进行排序:
javascriptlet sortedEmployees = _.orderBy(employees, ['age', 'hireYear'], ['asc', 'desc']);
在这个例子中,['age', 'hireYear']
指定了排序的顺序是先按 age
升序排列,如果 age
相同,则按照 hireYear
降序排列。对应的,['asc', 'desc']
分别指定了对应字段的排序方式。
打印排序后的结果:
javascriptconsole.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 回复