一个数组问题重复值合并问题

const ary = [{

    code: 1,

    num: 20,

}, {

    code: 1,

    num: 10,

}, {

    code: 2,

    num: 15,

}]

// 怎样得出下面结果?

const ary = [{

    code: 1,

    num: 30,

}, {

    code: 2,

    num: 15,

}]


慕娘9325324
浏览 457回答 5
5回答

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=[{&nbsp; &nbsp; &nbsp; &nbsp; code: 1,&nbsp; &nbsp; &nbsp; &nbsp; num: 20,&nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; &nbsp; code: 1,&nbsp; &nbsp; &nbsp; &nbsp; num: 10,&nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; &nbsp; code: 2,&nbsp; &nbsp; &nbsp; &nbsp; num: 15,&nbsp; &nbsp; }]&nbsp; &nbsp; var result={};&nbsp; &nbsp; for(i=0;i<abc.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; if(result[abc[i].code]){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[abc[i].code]+=abc[i].num;&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[abc[i].code]=abc[i].num;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; var keyvalue=[];&nbsp; &nbsp; for(var key in result){&nbsp; &nbsp; &nbsp; &nbsp; keyvalue.push({code:key,num:result[key]})&nbsp; &nbsp; }&nbsp; &nbsp; console.log(keyvalue)

森栏

new Set(arr)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript