• 数组去重的方法


    
    

     方法一:利用indexOf

    let arr = [1, 2, '1', 1, 2, 3, 4, 4, 5, 3];
    function arrRepeat(arr) {
        let newArr = []
        for(let i = 0; i < arr.length; i++) {
            if(newArr.indexOf(arr[i]) == -1) {
                newArr.push(arr[i])
            }
    
        }
        console.log(newArr)
    return newArr
    }
    arrRepeat(arr)

    方法二:利用  hasOwnProperty

    function arrRepeat(arr) {
        let obj = {};
        let newArray = [];
        for(let i = 0; i < arr.length; i++) {
          if(!obj.hasOwnProperty(arr[i])) {
              obj[arr[i]] = i;
            newArray.push(arr[i]);
        }
      }
      return newArray
    }
    console.log(arrRepeat([1,2,1,3,5,'','',3,6,'q','a','q','a']))      //[1, 2, 3, 5, "哈", 6, "q", "a"]

    方法三:利用ES6的set (一行代码数组去重)

    Set数据结构,它类似于数组,其成员的值都是唯一的。

    利用Array.from将Set结构转换成数组 

    let array = Array.from(new Set([1, 1, 1, 2, 3, 2, 4]));

    Set数据结构

    let arr = [1,2,3,3];
    let resultarr = [...new Set(arr)]; 
    console.log(resultarr); //[1,2,3]

    方法四: 双循环

    双层循环,外层循环元素,内层循环时比较值如果有相同的值则跳过,不相同则push进数组
     function arrRepeat(arr){
      let result = [],
      i,
      j,
      len = arr.length;
     for(i = 0; i < len; i++){
      for(j = i + 1; j < len; j++){
       if(arr[i] === arr[j]){
        j = ++i;
       }
      }
      result.push(arr[i]);
     }
     return result;
    }
    console.log(arrRepeat([1,2,1,3,5,'','',3,6,'q','a','q','a']))  // [2, 1, 5, "哈", 3, 6, "q", "a"]
  • 相关阅读:
    [leetcode] 110. 平衡二叉树
    [leetcode] 109. 有序链表转换二叉搜索树
    [leetcode] 108. 将有序数组转换为二叉搜索树
    [leetcode] 107. 二叉树的层次遍历 II
    [leetcode] 106. 从中序与后序遍历序列构造二叉树
    [leetcode] 105. 从前序与中序遍历序列构造二叉树
    [leetcode] 111. 二叉树的最小深度
    LeetCode
    LeetCode
    LeetCode
  • 原文地址:https://www.cnblogs.com/gaoht/p/9914525.html
Copyright © 2020-2023  润新知