数组去重

1.set
let unique = [...new Set([1,2,3,3,4,5,6,5])]
2.splice
let len = arr.length

for(let i = 0;i < len;i++) {
  for(let j = i + 1;j < len;j++) {
    if(arr[i] === arr[j]) {
      arr.splice(j,1)
      j--
      len--
    }
  }
}
console.log(arr)
  • j和len都要减一是因为当splice去掉一个元素时,数组的长度会减一,所以j和len都应该减一
3.indexOf
let res = []
for(let i = 0;i < len;i++) {
  if(res.indexOf(arr[i]) === -1) res.push(arr[i])
}
console.log(res)
4.includes
for(let i = 0;i < len;i++) {
  if(!res.includes(arr[i])) res.push(arr[i])
}
console.log(res)
5.filter
let res = arr.filter((item,index) => {
  return arr.indexOf(item) == index
})
console.log(res)
6.map&set
let map = new Map()
let res = []
for(let i = 0;i < arr.length;i++) {
  if(!map.has(arr[i])) {
    map.set(arr[i],true)
    res.push(arr[i])
  }
}
console.log(res)

你可能感兴趣的:(数组去重)