首页 > 其他分享 >数组根据某个字段 获取重复项 数组某个字段先累加再去重

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

时间:2023-03-15 14:47:31浏览次数:39  
标签:typeId index item 字段 num 数组 某个 type id

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

标签:typeId,index,item,字段,num,数组,某个,type,id
From: https://www.cnblogs.com/zyzlb/p/17218432.html

相关文章