gpt4 book ai didi

javascript - filterfirst 和 filterlast 函数与 lodash

转载 作者:行者123 更新时间:2023-11-29 21:16:29 24 4
gpt4 key购买 nike

假设我们有如下所示的一系列产品,产品按名称排序,然后按价格排序。我如何使用 lodash 获得每个类别中最便宜的产品或最昂贵的产品?我们需要类似 filterfirstfilterlast 的函数。

[
{
"productId": "123456",
"name": "Daiper",
"category": "Home",
"store": "store1",
"pricing": 10
},
{
"productId": "123457",
"name": "Daiper",
"category": "Home",
"store": "store2",
"pricing": 20
},
{
"productId": "123458",
"name": "Daiper",
"category": "Home",
"store": "store3",
"pricing": 30
},
{
"productId": "123466",
"name": "Paint",
"category": "Home",
"store": "store2",
"pricing": 25
},
{
"productId": "123467",
"name": "Paint",
"category": "Home",
"store": "store1",
"pricing": 36
},
{
"productId": "123468",
"name": "Paint",
"category": "Home",
"store": "store3",
"pricing": 80
}
]

最佳答案

您可以通过 name 属性 _.groupBy() 项目,然后将组数组 _.map() 到每个组的第一个或最后一个项目:

function filterGroups(groupIdProp, predicate) {
return function(arr) {
return _(arr)
.groupBy(groupIdProp)
.map(predicate)
.values();
}
}

var filterFirst = filterGroups('name', function(group) {
return group[0];
});

var filterLast = filterGroups('name', function(group) {
return group[group.length - 1];
})

var arr = [{
"productId": "123456",
"name": "Daiper",
"category": "Home",
"store": "store1",
"pricing": 10
}, {
"productId": "123457",
"name": "Daiper",
"category": "Home",
"store": "store2",
"pricing": 20
}, {
"productId": "123458",
"name": "Daiper",
"category": "Home",
"store": "store3",
"pricing": 30
}, {
"productId": "123466",
"name": "Paint",
"category": "Home",
"store": "store2",
"pricing": 25
}, {
"productId": "123467",
"name": "Paint",
"category": "Home",
"store": "store1",
"pricing": 36
}, {
"productId": "123468",
"name": "Paint",
"category": "Home",
"store": "store3",
"pricing": 80
}];

console.log('first', filterFirst(arr));

console.log('last', filterLast(arr));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

关于javascript - filterfirst 和 filterlast 函数与 lodash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39215931/

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