preface

Review several ways to de-duplicate arrays

1. Sort + adjacent comparison

Sort first, then save the first element to the new array, and each time the adjacent elements are compared, the different elements are added to the new array.

Empty objects {} and NaN cannot be removed

var arr = [1, 2, 3, 4, 3, 6, {}, {},NaN,NaN, undefined, undefined] function test1(arr) { arr.sort(); Let newArr = [arr[0]]; For (var I = 1; var I = 1; i < arr.length; I ++) {if(arr[I]! == newArr[newarr.length - 1]){//arr[I] is not equal to the last newArr, add to the new array. newArr.push(arr[i]) } } return newArr } console.log(test1(arr)) //[ 1, 2, 3, 4, 6, NaN, NaN, {}, {}, undefined ]Copy the code

2. Using the indexOf ()

If the iterated element is not in the new array (returns -1), it is added to the new array.

Empty objects {} and NaN cannot be removed

var arr = [1, 2, 3, 4, 3, 6, {}, {},NaN,NaN, undefined, undefined] function test2(arr) { arr.sort(); Let newArr = []; // Create a new array for(var I = 0; i < arr.length; {if(newarr.indexof (arr[I]) === -1){// add newarr. push(arr[I])}} return newArr; } console.log(test2(arr)) //[ 1, 2, 3, 4, 6, NaN, NaN, {}, {}, undefined ]Copy the code

3. includes()

Similar to indexOf(), the element is added to the new array if it is not there.

Cannot remove an empty object {}

var arr = [1, 2, 3, 4, 3, 6, {}, {},NaN,NaN, undefined, undefined] function test3(arr) { let newArr = []; // Create a new array for(var I = 0; i < arr.length; i++) { if(! Newarr.includes (arr[I])) {// If the element does not exist in the new array, Push (arr[I])}} return newArr} console.log(test3(arr)) //[1, 2, 3, 4, 6, {}, {}, undefined]Copy the code

4.filter() + includes()

Cannot remove an empty object {}

var arr = [1, 2, 3, 4, 3, 6, {}, {},NaN,NaN, undefined, undefined]

function test4(arr) {
    let newArr = [];
    newArr = arr.filter( item => {
       return newArr.includes(item) ? '' : newArr.push(item)
    })
    return newArr
}

console.log(test4(arr)) //[ 1, 2, 3, 4, 6, {}, {},NaN, undefined ]
Copy the code

5. reduce() + includes()

Cannot remove an empty object {}

var arr = [1, 2, 3, 4, 3, 6, {}, {},NaN,NaN, undefined, undefined] function test5(arr) { return arr.reduce((init, next) => { if(! init.includes(next)){ init.push(next) } return init },[]) } console.log(test5(arr)) // [ 1, 2, 3, 4, 6, {}, {},NaN, undefined ]Copy the code

6. new Set()

New Set() : pseudo-array, converted from array.from () to a real Array

Cannot remove an empty object {}

    var arr = [1, 2, 3, 4, 3, 6, {}, {},NaN,NaN, undefined, undefined]

var newArr = Array.from(new Set(arr))  // [ 1, 2, 3, 4, 6, {}, {}, NaN, undefined ]
Copy the code