javascript同数组里的对象比较,相等的话对象里的值累加。

var arr = [{"code":"111","num":1},{"code":"112","num":1},{"code":"111","num":3},{"code":"113","num":1},{"code":"113","num":5},{"code":"111","num":1}]
//像这样的一个数组,比较对象code,如果相等,取其num相加的值输出。
阅读 4.8k
4 个回答

这送分题啊
https://segmentfault.com/q/10...

function pollAdd(arr) {
  let res = [];
  let tmp = {};

  arr.forEach((v) => {
    if (!tmp.hasOwnProperty(v.code)) {
      tmp[v.code] = res.length;
      return res.push(Object.assign({}, v));
    }
    res[tmp[v.code]].num += v.num;
  });

  return res;
}
console.log(pollAdd(arr));

日经题。

function handle(arr) {
    var res = [],
        obj = {},
        index = 0;
    arr.forEach(val => {
        if (obj.hasOwnProperty(val.code)) {
            res[obj[val.code]].num += val.num;
        } else {
            obj[val.code] = index++;
            res.push({
                code: val.code,
                num: val.num
            });
        }
    });
    return res;
}
console.log(handle(arr))

function ad(arr){

var aa={};
arr.forEach(function(x){
    aa[x["code"]]=aa[x["code"]]||0;
    aa[x["code"]]+=x["num"]
})
return aa

}
console.log(aa)

var arr = [
{"code":"111","num":1},
{"code":"112","num":1},
{"code":"111","num":3},
{"code":"113","num":1},
{"code":"113","num":5},
{"code":"111","num":1}
]
for(var i=0; i< arr.length; i++){
var sum = arr[i].num;
var arrOld = arr.concat([])
for(var j=arr.length-1; j>i; j--){

if(arr[i].code === arr[j].code){
  sum += arr[j].num
  arrOld.splice(j,1)
}

}
console.log(arr[i].code,sum, 'n')
arr = arrOld
}

推荐问题
宣传栏