在 JavaScript 中过滤唯一数组值并求和
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个像这样的数组数组 −
const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];
我们应该编写一个接受这样一个数组的函数。请注意,所有子数组中都恰好有三个元素。
我们的函数应该过滤掉第一个元素为重复值的子数组。此外,对于子数组,我们删除了它们,并将它们的第三个元素添加到其现有的非重复对应元素中。
因此,对于上述数组,输出应如下所示 −
const output = [[12345, "product", "25"],[1234567, "other", "10"]];
示例
其代码为 −
const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567,
"other", "10"]];
const addSimilar = (arr = []) => {
const res = [];
const map = {};
arr.forEach(el => {
const [id, name, amount] = el;
if(map.hasOwnProperty(id)){
const newAmount = +amount + +res[map[id] - 1][2];
res[map[id] - 1][2] = '' + newAmount;
}else{
map[id] = res.push(el);
}
});
return res;
}
console.log(addSimilar(arr));
输出
控制台中的输出将是 −
[ [ 12345, 'product', '25' ], [ 1234567, 'other', '10' ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

