思路:
1遍历这个数组 然后把每个对象里面的年月日拼起来 拼成一个新的key 然后返回一个新的数组 就类似与['onlyKey': '201943', datas: {year:2019,month:4,day:3,ms:0,last:1,rateChange:-3.14}],
2然后再遍历这个新数组 ,将数据写入对象里,方法是 'onlyKey'作为对象名, 对象名已存在(代表日期已存在),数据就加和,不存在,就加入对象。
3再将对象转化为数组
let arr = [
{year:2019,month:4,day:16,ms:6.33,last:0,rateChange:0},
{year:2019,month:4,day:17,ms:2.44,last:0,rateChange:0},
{year:2019,month:4,day:18,ms:7.41,last:0,rateChange:0},
{year:2019,month:4,day:3,ms:-7.41,last:0,rateChange:3},
{year:2019,month:4,day:5,ms:0,last:7.6,rateChange:0},
{year:2019,month:4,day:5,ms:8.3,last:0,rateChange:0},
{year:2019,month:4,day:3,ms:0,last:1,rateChange:-3.14},
]
let addData=(arr)=>{
let filterarr=[]
arr.map(
p=>{
filterarr.push({'onlyKey':p.year.toString()+p.month.toString()+p.day.toString(),'datas':p})
}
)
console.log("filterarr",filterarr)
let newObj={}
filterarr.map(
(p,index)=>{
if(newObj[p.onlyKey]!==undefined){
let o= newObj[p.onlyKey].datas
let d=p.datas
d.ms? o.ms=Number(o.ms)+ Number(d.ms) : o.ms
d.last? o.last=Number(o.last)+ Number(d.last) : o.last
d.rateChange? o.rateChange=Number(o.rateChange)+ Number(d.rateChange) : o.rateChange
newObj[p.onlyKey].datas = o
}else{
newObj[`${p.onlyKey}`]=p
}
}
)
let newArr=[]
for(let p in newObj){
newArr.push(
newObj[p]
)
}
return newArr
console.log("最后newArr",newArr)
}
addData(arr);
打印结果