这是我正在尝试做的事情:
我有这两个数组作为输入。我想将它们组合起来,并合并具有相同“类型”属性的对象,并为这些对象添加数量。 因此,对于下面的这两个数组,我在每个数组中都有一个“类型”等于 veggie 的对象。生成的数组将包含一个具有“类型”蔬菜的对象,且关联的数量等于 30 (27+3)。
const arr1 = [{"quantity": 27, "type": "veggie"}, {"quantity": 191, "type": "meat"}, {"quantity": 3, "type": "fruit"}];
const arr2 = [{"quantity": 13, "type": "fish"}, {"quantity": 191, "type": "dairy"}, {"quantity": 3, "type": "veggie"}];
const all = [...arr1, ...arr2];
function mergeArrays(arr) {
const res = arr.reduce(function(acc, curr) {
const findTagIndex = acc.findIndex((item) => item.type === curr.type);
if (findTagIndex === -1) {
acc.push(curr)
} else {
acc[findTagIndex].quantity += curr.quantity
}
return acc;
}, []);
return res;
}
const newArray = mergeArrays(all);
console.log(newArray)//[{数量:191,类型:“肉”},{数量:30,类型:“蔬菜”},{数量:3,类型:“水果”} ,{数量:13,类型:“鱼”},{数量:191,类型:“乳制品”}];
我不明白并且一直困惑的是,数组的合并似乎会改变arr1
。
如果我在获取 newArray 之前和之后控制台 arr1 的日志,它将分别记录。 27 和 30 种蔬菜。这是怎么回事?
有什么建议我做错了什么吗?我还能怎样继续?我尝试了几件事。我尝试使用forEach
。结果相同。
最佳答案
您将第一个数组中的对象插入另一个数组,因此两个数组都保存对相同对象的引用。您可以在推送时轻松(浅)复制对象:
acc.push({ ...curr });
这是我的做法(时间复杂度为 O(n)):
const quantityByType = new Map();
for(const { type, quantity } of [...arr1, ...arr2]) {
amountByType.set(type, quantity + (quantityByType.get(type) || 0));
}
const result = [...quantityByType.entries()]
.map(([type, quantity]) => ({ type, quantity }));
关于javascript - 合并数组,为什么我的输入数组发生了变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58796322/