10种方式实现数组的去重

1 双层for循环

let arr = [1,1,2,3,3,4,5,6];
function uniqueArr(arr) {
  for(let i = 0; i < arr.length; i++ ) {
    for(let j = i+1; j < arr.length; j++) {
      if(arr[i] == arr[j]) {
        arr.splice(j,1);
        j--;
      }
    }
  }
  return arr
}
uniqueArr(arr)

2 indexOf+for in 实现数组去重

let arr = [1,1,2,3,3,4,5,6];
function uniqueArr(arr) {
  let arr1 = [];
  for(let i in arr) {
    if(arr1.indexOf(arr[i]) === -1) {
      arr1.push(arr[i])
    }
  }
  return arr1
}
uniqueArr(arr)

3 includes+for in 实现数组去重

let arr = [1,1,2,3,3,4,5,6];
function uniqueArr(arr) {
  let arr1 = [];
  for(let i in arr) {
    if(!arr1.includes(arr[i])) {
      arr1.push(arr[i])
    }
  }
  return arr1
}
uniqueArr(arr) // [1, 2, 3, 4, 5, 6]

4 filters + indexOf

let arr = [1,1,2,3,3,4,5,6];
function uniqueArr(arr) {
  return arr.filter((item,index,array) => array.indexOf(item) === index)
}
uniqueArr(arr) // [1, 2, 3, 4, 5, 6]

5 for循环+ object属性的独一无二性实现数组去重

let arr = [1,1,2,3,3,4,5,6];
function uniqueArr(arr) {
  let obj = {};
  let arr1 = []
  for(let i in arr) {
    if(!obj[arr[i]]) {
      arr1.push(arr[i])
      obj[i] = true;
    }
  }
  return arr1
}
uniqueArr(arr) // [1, 2, 3, 4, 5, 6]

6 map+for循环(map类似于对象,里边不会出现相同的key值)

let arr = [1,1,2,3,3,4,5,6];
function uniqueArr(arr) {
  let map = new Map();
  let arr1 = []
  for (let i in arr) {
    if(!map.has(arr[i])) {
      map.set(arr[i],1)
      arr1.push(arr[i])
    }
  }
  return arr1
}
uniqueArr(arr) // [1, 2, 3, 4, 5, 6]

7 reduce + indexOf()

let arr = [1,1,2,3,3,4,5,6];
function uniqueArr(arr) {
  return arr.reduce((prev,item) => prev.indexOf(item) == -1 ? [...prev,item]: prev,[])
}
uniqueArr(arr) // [1, 2, 3, 4, 5, 6]

8 reduce + includes()

let arr = [1,1,2,3,3,4,5,6];
function uniqueArr(arr) {
  return arr.reduce((prev,item) => prev.includes(item) ? prev : [...prev,item],[])
}
uniqueArr(arr) // [1, 2, 3, 4, 5, 6]

9 sort()排序,相邻的元素进行对比

let arr = [1,1,2,3,3,4,5,6];
function uniqueArr(arr) {
  arr = arr.sort();
  let arr1 = [arr[0]]
  for(let i = 1; i < arr.length;  i++) {
    if(arr[i] !== arr[i-1]) {
       arr1.push(arr[i])
    }
  }
  return arr1
}
uniqueArr(arr) // [1, 2, 3, 4, 5, 6]

10 new Set()

let arr = [1,1,2,3,3,4,5,6];
let uniqueArr = (arr) => [...new Set(arr)]
uniqueArr(arr)

上一篇:模拟实现拷贝字符串


下一篇:数组和函数