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

要被js搞死
  • 27
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.1k
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
}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏