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相加的值输出。
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相加的值输出。
日经题。
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
}
8 回答4.6k 阅读✓ 已解决
6 回答3.4k 阅读✓ 已解决
5 回答2.8k 阅读✓ 已解决
5 回答6.3k 阅读✓ 已解决
4 回答2.2k 阅读✓ 已解决
4 回答2.8k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
这送分题啊
https://segmentfault.com/q/10...