目录

数组去重

数组去重一般来说就这么几种方法,理解代码,记住就好!Map、Set、reduce、filter~

方法1

const arr = [3, 1, 1, 2, 5, 9, 3, 0]
const deduplication1 = arr => {
  let map = new Map()
  arr.forEach(v => map.set(v, 1))
  return [...map.keys()]
};
console.log(deduplication1(arr));

方法2

const arr = [3, 1, 1, 2, 5, 9, 3, 0]
const deduplication2 = arr => [...new Set(arr)];
console.log(deduplication2(arr))

方法3

const arr = [3, 1, 1, 2, 5, 9, 3, 0]
const deduplication3 = arr => arr.reduce((temp, v) => temp.includes(v) ? temp : [...temp, v], [])
 
console.log(deduplication3(arr))

方法4

const arr = [3, 1, 1, 2, 5, 9, 3, 0]
const deduplication4 = arr => arr.filter((val, index) => arr.indexOf(val) === index)
console.log(deduplication4(arr))

方法5

对原数组进行操作

let arr = [3, 0, 0, 1, 1, 2, 3, 3, 3, 5, 5]
 
function deduplication(arr) {
  let hash = {}
  for(let i=0; i<arr.length; i++) {
    if(!hash[arr[i]]) {
      hash[arr[i]] = 1
    } else {
      arr.splice(i, 1)
      i--
    }
  }
  return arr
}
 
let arr2 = deduplication(arr)
console.log(arr2)
console.log(arr)
console.log(arr === arr2)