gpt4 book ai didi

javascript - 过滤器列表 - 根据计数键删除两个重复项中较小的一个

转载 作者:行者123 更新时间:2023-11-30 11:19:02 25 4
gpt4 key购买 nike

在这个问题中,我有一个杂货 list ,我想通过删除重复项并保留只有计数较高的副本。然后还保留不重复的项目。我最终通过巧合的纯编程完成了这项工作,并且想学习解决这个问题的更好方法。我在下面评论了我的代码,以分享发生的事情和我的想法过程。如果有人有更好的方法来解决这个问题,我很乐意学习。

var groceryList = [
{
item: "Bananas",
count: 4
},
{
item: "Bananas",
count: 3
},
{
item: "Brussel Sprouts",
count: 2
},
{
item: "Bacon",
count: 100
},
{
item: "Beans",
count: 19
},
{
item: "Beans",
count: 5
}
]

const seen = {}
const newList = []
var removeDups = []
const list = groceryList.map(function(item) {
// if we haven't this item before (via check on item name) push it into seen object
// also push it to newList array
if (!seen[item.item]) {
seen[item.item] = item
newList.push(item)
}
// if we have seen the item during iteration...
else if (seen[item.item]) {
// remove it from the newList array
removeDups = newList.filter(function(listItem) {
if (listItem.item == item.item) {
console.log('matched');
} else {
return true
}
})

// and push in the item with the higher count
if (seen[item.item].count > item.count) {
removeDups.push(seen[item.item])
} else {
removeDups.push(item)
}
}
})

console.log(removeDups);

最佳答案

当输入项和输出项不一定是一对一时,您可以使用 reduce 将数组简洁地转换为另一个数组(或对象):

var groceryList=[{item:"Bananas",count:4},{item:"Bananas",count:3},{item:"Brussel Sprouts",count:2},{item:"Bacon",count:100},{item:"Beans",count:19},{item:"Beans",count:5}]
const filteredListObj = groceryList.reduce((a, { item, count }) => {
// this is a new item, or a duplicate with a greater quantity:
if (!a[item] || a[item].count < count) a[item] = { item, count };
return a;
}, {});
const filteredList = Object.values(filteredListObj);
console.log(filteredList);

关于javascript - 过滤器列表 - 根据计数键删除两个重复项中较小的一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50518070/

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