按Lodash 2.x中的多个字段排序
Sort by multiple fields in Lodash 2.x
假设此数组:
var members = [
{firstName: 'Michael', weight: 2},
{firstName: 'Thierry', weight: 1},
{firstName: 'Steph', weight: 3},
{firstName: 'Jordan', weight: 3},
{firstName: 'John', weight: 2}
];
我想按权重排序,对于每种权重,都按firstNames排序(嵌套排序)。
结果是:
[
{firstName: 'Thierry', weight: 1},
{firstName: 'John', weight: 2},
{firstName: 'Michael', weight: 2},
{firstName: 'Jordan', weight: 3},
{firstName: 'Steph', weight: 3}
];
我使用Lodash 2.4.1:快速实现了这一点
return _.chain(members)
.groupBy('weight')
.pairs()
.sortBy(function(e) {
return e[0];
})
.map(function(e){
return e[1];
})
.map(function(e){
return _.sortBy(e, 'firstName')
})
.flatten()
.value();
使用Lodash 2.4.1有更好的方法来实现它吗?
您可以链接两种排序:
_(members).sortBy('firstName').sortBy('weight').value()
它甚至在普通的Javascript中都很短。
var members = [
{ firstName: 'Michael', weight: 2 },
{ firstName: 'Thierry', weight: 1 },
{ firstName: 'Steph', weight: 3 },
{ firstName: 'Jordan', weight: 3 },
{ firstName: 'John', weight: 2 }
];
members.sort(function (a, b) {
return a.weight - b.weight || a.firstName.localeCompare(b.firstName);
});
document.write('<pre>' + JSON.stringify(members, 0, 4) + '</pre>');
如果您使用的是旧版本的lodash ,则使用lodash的另一种变体
var members = [
{ firstName: 'Michael', weight: 2 },
{ firstName: 'Thierry', weight: 1 },
{ firstName: 'Steph', weight: 3 },
{ firstName: 'Jordan', weight: 3 },
{ firstName: 'John', weight: 2 }
];
var result=_.sortBy(members,['firstname','weight'],['asc','asc']);
console.log('result',result);
相关文章:
- 高级自定义字段按单选按钮值排序
- 如何指定我按哪个字段排序
- 按字段值作为参数对数组中的对象进行排序
- 如何通过三个不同的字段对javascript数组进行排序
- Mongoose,按填充字段对查询进行排序
- 使用ramda.js中的嵌套字段进行排序
- 我需要使用mongodb本机驱动程序来查找按时间戳字段排序的不同id
- 如何在JavaScript中对具有多个字段值的对象数组进行排序
- 如何在客户端通过多个字段对java对象进行排序
- 当字段的值可以为空时对 javascript 数组进行排序
- 使用猫鼬.js嵌套数组中的字段排序
- 选择下拉列表时,按角度中的多个字段排序
- Js lodash 按更深的字段排序
- AngularJS 按整数字段排序无法正常工作
- 选择包含每个唯一字段值的行,并按另一个具有限制的字段排序
- 按Lodash 2.x中的多个字段排序
- 在javascript中实现搜索结果的多字段排序
- n -repeat track by $index打破图像字段排序
- 如何使用lodash/underscore按多个嵌套字段排序?
- 在ExtJS中选择布尔字段排序的方向类型