gpt4 book ai didi

javascript - 在 Lodash 2.x 中按多个字段排序

转载 作者:搜寻专家 更新时间:2023-11-01 05:00:12 27 4
gpt4 key购买 nike

假设这个数组:

var members = [
{firstName: 'Michael', weight: 2},
{firstName: 'Thierry', weight: 1},
{firstName: 'Steph', weight: 3},
{firstName: 'Jordan', weight: 3},
{firstName: 'John', weight: 2}
];

我想按重量排序,对于每种重量,按名字排序(嵌套排序)。

结果是:

[
{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 - 在 Lodash 2.x 中按多个字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33927894/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com