An array problem duplicate value merging problem

const ary = [{
    code: 1,
    num: 20,
}, {
    code: 1,
    num: 10,
}, {
    code: 2,
    num: 15,
}]
// 
const ary = [{
    code: 1,
    num: 30,
}, {
    code: 2,
    num: 15,
}]
Mar.15,2021

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;iPP){
        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)


learn from JS to implement array deduplication (six methods)
Link description

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b35e0e-2bfd9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b35e0e-2bfd9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?