How to implement array de-duplication? Suppose you have an array array = [1,5,2,3,4,2,3,1,3,4] and you write a function unique that gives unique(array) the value of [1,5,2,3,4].

Method 1: Use indexOf to remove weights

function unique(arr) {
    if(!Array.isArray(arr)) {
        console.log('type error! ')
        return
    }
    let array = []
    for(let i = 0; i < arr.length; i++) {
        if(array.indexOf(arr[i]) === -1) {
            array.push(arr[i])
        }
    }
    return array
}
Copy the code

Cons: Inability to do NaN de-duplication.

Method 2: Map data structure is used for deduplication

function unique(arr) {
    let map = new Map(a)let array = new Array(a)for(let i = 0; i < arr.length; i++) {
        if(map.has(arr[i])) {
            map.set(arr[i], true)}else {
            map.set(arr[i], false)
            array.push(arr[i])
        }
    }
    return array
}
Copy the code

Cons: API is too new to be supported by older browsers.

Method three: refer to the principle of counting sort

unique = (array) = > {
    const hash = []
    for(let i=0; i<array.length; i++){ hash[array[i]] =true
    }
    const result = []
    for(let k in hash){
        result.push(k)
    }
    return result
}
Copy the code

Disadvantages: Supports only numeric or string arrays, if the array contains objects, such as array = [{number:1}, 2], error.

Method 4: Use Set

function unique(arr) {
    return Array.from(new Set(arr)) // Convert a Set structure to an Array using array. from
}
// The above code can also be simplified as:
[...new Set(arr)]
Copy the code

Cons: API is too new to be supported by older browsers.

Method 5: Support object deduplication

function unique(arr) {
    const map = new Map(a)return arr.filter( item= >! map.has(JSON.stringify(item)) && map.set(JSON.stringify(item), 1))}Copy the code

To be added.