gpt4 book ai didi

Javascript:对集合中的对象求和

转载 作者:行者123 更新时间:2023-11-29 17:13:29 27 4
gpt4 key购买 nike

我正在寻找一种在 javascript 中整合对象集合的方法。例如我有一个集合:

inventory = [ 
{count: 1, type: "Apple"},
{count: 2, type: "Orange"},
{count: 1, type: "Berry"},
{count: 2, type: "Orange"},
{count: 3, type: "Berry"}
]

我想要结束的是:

   inventory = [
{count: 1, type: "Apple"},
{count: 4, type: "Orange"},
{count: 4, type: "Berry"}
]

有没有一种优雅的方法可以做到这一点,它不需要获取类型列表、在我的集合中搜索这些类型、对值求和并用求和值创建一个新数组?

最佳答案

它不是很漂亮,但是这样就可以了。它创建了一个项目类型/计数的字典,以及一个最终总和的列表。 inventoryDict 用于轻松查找现有计数,而 summedInventory 保存最终的求和项目列表。

var inventory = [ /* ... */ ];
var summedInventory = [];
var inventoryDict = {};

for (var i = 0; i < inventory.length; i++) {
var item = inventory[i];
if (!(item.type in inventoryDict)) {
inventoryDict[item.type] = {type: item.type, count: 0};
summedInventory.push(inventoryDict[item.type]);
}
inventoryDict[item.type].count += item.count;
}

这是假设您不想就地改变库存项目 - 如果您不介意改变项目,可以稍微简化循环。

为了避免中间变量并以更实用的方式进行操作,您可以使用 Array.reduce:

var newInventory = inventory.reduce(function(acc, item) {
var summedInventory = acc[0], inventoryDict = acc[1];

if (!(item.type in inventoryDict)) {
inventoryDict[item.type] = {type: item.type, count: 0};
summedInventory.push(inventoryDict[item.type]);
}

inventoryDict[item.type].count += item.count;
return acc;
}, [[], {}])[0];

关于Javascript:对集合中的对象求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19946010/

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