zoukankan      html  css  js  c++  java
  • es6数组(子项为对象)去重方案总结 js数组去重

    1.业务需求:

    vue项目需要对数组(子项是对象)进行去重。

    2.解决方案

    2.1使用.filter方法对复杂结构的数组(子项为对象)进行去重:

    // 去重函数(test:数组)
    dropFilter(test) {
      // ele:当前元素的值,index:当前元素的索引值,arr:原数组
      return test.filter((ele,index,arr)=>{
      // 通过索引筛掉相同的项 sysOrganizeId为对象中唯一值
       return arr.findIndex(item=>item.sysOrganizeId===ele.sysOrganizeId) === index
      })
    },
    

    2.2使用.reduce方法对复杂结构的数组(子项为对象)进行去重:

    // 去重函数(list:数组) 
    dropReduce(list) {
      // 定义一个空对象,利用对象的键的唯一进行去重
      let obj = {}
      // 去重(cur:init默认list,next:数组子项,index:表示当前正在处理的数组元素的索引,arr:表示原数组) sysResourcesId为对象中唯一值
      return list.reduce((cur,next,index,arr) => {
        obj[next.sysResourcesId]?"":obj[next.sysResourcesId]=true && cur.push(next)
        return cur
      }, [])
    },
    

    2.3使用.reduce方法对简单结构的数组(子项为数字)进行去重:

    let arr = [1,2,3,4,5,1,2,1];
    // indexOf()判断数组第一次出现的下标
    var newArr = arr.reduce((cur, next)=> {
    cur.indexOf(next) === -1 && cur.push(next);
    return cur;
    },[]);
    

    特此感谢https://blog.csdn.net/qq_34917408/article/details/107493740?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2aggregatepagefirst_rank_v2~rank_aggregation-10-107493740.pc_agg_rank_aggregation&utm_term=list+vue+%E5%8E%BB%E9%87%8D&spm=1000.2123.3001.4430作者

  • 相关阅读:
    SCUT
    SCUT
    SCUT
    ???
    Codeforces
    SCUT
    SCUT
    SCUT
    SCUT
    2019牛客暑期多校训练营(第八场)
  • 原文地址:https://www.cnblogs.com/zhaoxiangjun/p/14821214.html
Copyright © 2011-2022 走看看