例如:

const arr = [
    {id:1,typeId:1,num:2},
    {id:2,typeId:1,num:5},
    {id:3,typeId:2,num:2},
    {id:4,typeId:2,num:1},
    {id:5,typeId:3,num:2},
    {id:6,typeId:3,num:2},
    {id:7,typeId:3,num:2},
];

如果只是去重使用map()和filter()方法就行

const res = new Map();
arr.filter((item)=>{
    !res.has(item.typeId) && res.set(item.typeId,1)
});

现在我想要的是能够去重,但相同的typeId的num要累加
最后的结果希望是这样的:

const arr = [
    {id:1,typeId:1,num:7},
    {id:3,typeId:2,num:3},
    {id:5,typeId:3,num:6},
];

 解决方法:

arr.reduce((list, item)=>{
    if(res.has(item.typeId)){
        res.get(item.typeId).num += item.num
    }else{
        let o = {...item}
        list.push(o)
        res.set(item.typeId, o)
    }
    
    return list
}, []);

showtooltip.com

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2020-10-10
  • 2022-12-23
相关资源
相似解决方案