-
largeQ
const ary = [{ code: 1, num: 20}, { code: 1, num: 10}, { code: 2, num: 15}]function merge (list) { let result = [] let cache = {} list.forEach(item => { let key = item.code let index = cache[key] if (index !== undefined) { result[index].num += item.num } else { result.push(Object.assign({}, item)) cache[key] = result.length - 1 } }) return result}merge(list)
-
慕森王
function merge(arr) { let res = {}; for(let item of arr) { if(res[item.code]) res[item.code].num += item.num; else res[item.code] = { code: item.code, num: item.num }; // Avoid modifying the original object. } return Object.values(res);}
-
神不在的星期二
var abc=[{ code: 1, num: 20, }, { code: 1, num: 10, }, { code: 2, num: 15, }] var result={}; for(i=0;i<abc.length;i++){ if(result[abc[i].code]){ result[abc[i].code]+=abc[i].num; }else{ result[abc[i].code]=abc[i].num; } } var keyvalue=[]; for(var key in result){ keyvalue.push({code:key,num:result[key]}) } console.log(keyvalue)
-
森栏
new Set(arr)