JavaScript数组---常用数组去重

1、ES6简单数组去重

const arr = [1,1,2,3,4,5,6,6,6]
const newArr = Array.from(new Set(arr))  // [1,2,3,4,5,6]
const newArr = [...new Set(arr)]  // [1,2,3,4,5,6]

2、reduce去重

const arr = [1,1,2,3,4,5,6,6,6]
const newArr = arr.reduce((pre, cur) => {
    if(!pre.includes(cur)){
        pre.push(cur)
    }
     return pre
}, [])
console.log(newArr)  //  [1, 2, 3, 4, 5, 6]

3、for循环去重

const arr = [1,1,2,3,4,5,6,6,6]
let newArr = []
for(let item of arr){
    if(newArr.indexOf(item) == -1){
        newArr.push(item)
    }
}
console.log(newArr)  //  [1, 2, 3, 4, 5, 6]

4、sort + for循环去重

const arr = [1,1,2,3,4,5,6,6,6]
arr.sort()
let newArr = [arr[0]]
for(let i = 1; i < arr.length; i++){
    if(arr[i] !== arr[i-1]){
        newArr.push(arr[i])
    }
}
console.log(newArr)  //  [1, 2, 3, 4, 5, 6]

其他利用for循环去重的换个思路就可以了

5、filter去重

const arr = [1,1,2,3,4,5,6,6,6]
const newArr = arr.filter((item, index, arr) => {
return arr.indexOf(item) === index
})
console.log(newArr)  //  [1, 2, 3, 4, 5, 6]

你可能感兴趣的:(JavaScript数组---常用数组去重)