js操作之reduce
1.遍历求和
const arr=[
{id:1,value:1},
{id:2,value:1},
{id:3,value:1},
{id:3,value:2},
{id:2,value:5}
]
预计输出
[
{id:1,value:1},
{id:2,value:6},
{id:3,value:3},
]
2.方法reduce
arr.reduce((pre,next)=>{
let findIndex=pre.findIndex(i=>i.id===next.id); // 查找pre中是否存在当前item的信息
if(findIndex>-1){
pre[findIndex].value+=next.value; // 存在的话,将item的值相加
} else {
pre.push(next) // 不存在则将item推到返回的结果数组中
}
return pre
},[]); // []: 返回数据的形式为数组
仅此记录,以温习。