• 数组去重


      记得刚开始我做数组去重的时候,就是定义一个新数组,然后遍历数组,如果新数组中不存在则push进去。

    let arr=[1,2,3,1,2,3];
    let result=[];
    arr.forEach(item=>{
        if(result.indexOf(item)==-1){
           result.push(item);        
        }
    })
    console.log(result);//[1,2,3]
    

      后来在Es6中出了一个Set,可以简单的实现数组去重

    const arr = ['张三','张三','三张三']
    let set = new Set(arr); // set 自带去重
    console.log([...set]);//["张三", "三张三"]
    console.error(Array.from(set)); // [ '张三', '三张三' ]

      如果面对复杂类型的数组去重,上面的方法不够用了,以是有了下面这种方法

    let log = console.log.bind(console);
    let person = [
         {id: 0, name: "小明"},
         {id: 1, name: "小张"},
         {id: 2, name: "小李"},
         {id: 3, name: "小孙"},
         {id: 1, name: "小周"},
         {id: 2, name: "小陈"},
         {id: 0, name: "重复"},   
    ];
    
    let obj = {};
    
    person = person.reduce((cur,next) => {
        obj[next.id] ? "" : (obj[next.id] = true , cur.push(next));
        return cur;
    },[]) //设置cur默认类型为数组,并且初始值为空的数组
    log(person);
  • 相关阅读:
    顧客満足度調査
    GeoStTool.dll过滤图层
    GeoStTool.ini相关技术要点
    GeoStTool.dll与RasterServer通信
    hdu 1007 Quoit Design
    hdu 4325 Flowers
    hdu 2516 取石子游戏
    hdu 1006 Tick and Tick
    CodeForces 101A Homework
    ZOJ Problem Set 1879
  • 原文地址:https://www.cnblogs.com/gitByLegend/p/11399232.html
Copyright © 2020-2023  润新知