数组去重-Map实现

作者: dear智子 | 来源:发表于2020-05-25 16:33 被阅读0次

    https://segmentfault.com/a/1190000015923301?utm_source=tag-newest

    function arrayNonRepeatfy(arr) {
      let hashMap = new Map();
      let result = new Array();  // 数组用于返回结果
      for (let i = 0; i < arr.length; i++) {
        if(hashMap.has(arr[i])) { // 判断 hashMap 中是否已有该 key 值
          hashMap.set(arr[i], true);  // 后面的true 代表该 key 值在原始数组中重复了,false反之
        } else {  // 如果 hashMap 中没有该 key 值,添加
          hashMap.set(arr[i], false);  
          result.push(arr[i]);
        }
      } 
      return result;
    }
    
    let arr = [1, 1, 1, 2, 3, 3, 4, 5, 5, "a", "b", "a"];
    console.log(arrayNonRepeatfy(arr)); // [ 1, 2, 3, 4, 5, 'a', 'b' ]
    

    filter

    function unique(arr) {
        //定义常量 res,值为一个Map对象实例
        const res = new Map();
        
        //返回arr数组过滤后的结果,结果为一个数组
        //过滤条件是,如果res中没有某个键,就设置这个键的值为1
        return arr.filter((a) => !res.has(a) && res.set(a, 1))
    }
    

    相关文章

      网友评论

        本文标题:数组去重-Map实现

        本文链接:https://www.haomeiwen.com/subject/axnyahtx.html