对数组重复值求和 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 23:40:17
假设,我们有一个像这样的对象数组 −
const arr = [
{'ID-01':1},
{'ID-02':3},
{'ID-01':3},
{'ID-02':5}
];
我们需要将所有这些具有相同键的对象的值相加
因此,对于这个数组,输出应该是 −
const output = [{'ID-01':4}, {'ID-02':8}];
我们将循环遍历数组,检查是否存在具有相同键的现有对象,如果存在,我们将为其添加值,否则我们将新对象推送到数组。
示例
以下是代码 −
const arr = [
{'ID-01':1},
{'ID-02':3},
{'ID-01':3},
{'ID-02':5}
];
const indexOf = function(key){
return this.findIndex(el => typeof el[key] === 'number')
};
Array.prototype.indexOf = indexOf;
const groupArray = arr => {
const res = [];
for(let i = 0; i < arr.length; i++){
const key = Object.keys(arr[i])[0];
const ind = res.indexOf(key);
if(ind !== -1){
res[ind][key] += arr[i][key];
}else{
res.push(arr[i]);
};
};
return res;
};
console.log(groupArray(arr));
输出
这将在控制台中产生以下输出 −
[ { 'ID-01': 4 }, { 'ID-02': 8 } ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

