数组去重

数组去重

Array.from(new Set(arr))

let arr = [1,1,2,2,3,3]
let brr = Array.from(new Set(arr))
// let brr = [...new Set(arr)]
console.log(brr) //[1,2,3]

for嵌套for,然后使用splice去重

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--
    }
  }
}
console.log(arr)

利用indexOf去重

let brr = []
for(let i = 0; i < arr.length; i++) {
  if(arr.indexOf(arr[i]) === -1) {
    brr.push(arr[i])
  }
}
console.log(brr)

利用includes去重

let brr = []
for(let i = 0; i < arr.length; i++) {
  if( !brr.includes(arr[i])) {
    brr.push(arr[i])
  }
}
console.log(brr)

利用filter()去重

let brr = arr.filter((item, index, arr) => {
  return arr.indexOf(item, 0) === index
})
console.log(brr)

分割线

使用reduce方法去重:

let arr = [1, 2, 3, 3, 4, 5, 5 ,6]
const obj = {}
const brr = arr.reduce((pre, cur) => {
  obj[cur]?'':pre.push(cur);
  obj[cur] = true;
  return pre;
}, []);
posted @ 2021-09-23 09:46  卿六  阅读(35)  评论(0编辑  收藏  举报