数组根据某个字段 获取重复项 数组某个字段先累加再去重

1.获取重复项 不重复项

const List=[ { name:'大学女友', age:20, type:'正宫' }, { name:'隔壁姐姐', age:24, type:'微信' }, { name:'楼上阿姨', age:32, type:'阿姨' }, { name:'小区妹妹', age:18, type:'微信' }, ] let key = {} //存储的 key 是type的值,value是在indeces中对应数组的下标 let indices = [] //数组中每一个值是一个数组,数组中的每一个元素是原数组中相同type的下标 List.map((item, index) => { //根据对应字段 分类(type) let type= item.type let _index = key[type] if (_index !== undefined) { indices[_index].push(index) } else { key[type] = indices.length indices.push([index]) } }) // 归类结果 let result = [] indices.map((item) => { item.map((index) => { //result.push(List[index]) 相同项排序在一起 //if (item.length > 1) {} 只要重复项 //if (item.length == 1){} 只要单独项 //我这里需要重复项 根据业务处理 if (item.length > 1) { result.push(List[index]) } }) }) //结果 //[{ name:'隔壁姐姐',age:24,type:'微信'}, {name:'小区妹妹',age:18,type:'微信'}]

  2.累加去重

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},
];



let newArr=Object.values(arr.reduce((res,v)=>{
    if(res[v.typeId]) res[v.typeId].num += v.num;
    else res[v.typeId] = v;
    return res;
}, {}))

console.log(newArr)

//----结果
{id:1,typeId:1,num:7},
{id:3,typeId:2,num:3},
{id:5,typeId:3,num:6},

  转载于: https://blog.csdn.net/m0_49256439/article/details/126246914

  转载于: https://segmentfault.com/q/1010000039780071?utm_source=sf-hot-question

posted @ 2023-03-15 14:33  热爱前端的5号机器  阅读(44)  评论(0编辑  收藏  举报