js - implement deduplication array

Method One: Create a new temporary array to hold the elements already in the array

Array.prototype.unique = function(){
        let uniqueArr = [];
        for(let i = 0; i < this.length; i++){
            //如果当前数组的第i个元素已经保存进了临时数组,那么跳过
            if(uniqueArr.indexOf(this[i]) === -1){
                uniqueArr.push(this[i])
            }
        }
        return uniqueArr
    }

Method Two: Use hash table to store existing element

Array.prototype.unique = function(){
        let uniqueArr = [];
        let hash = []; //定义hash哈希表
        for(let i = 0; i < this.length; i++){
            //如果hash表中没有当前数组的第i个元素,则将它存入哈希表
            if(!hash[this[i]]){
                hash[this[i]] = true;
                uniqueArr.push(this[i])
            }
        }
        return uniqueArr
    }

Method three: indexof position determination using array element first appears is the current position

Array.prototype.unique = function(){
        let uniqueArr = [];
        for(let i = 0; i < this.length; i++){
            //如果当前数组元素在数组中出现的第一次位置不是i说明是重复元素
            if(this.indexOf(this[i]) === i){
                uniqueArr.push(this[i])
            }
            
        }
        return uniqueArr
    }
    console.log(a.unique())

Method four: first re-ordering again

Array.prototype.unique = function(){
        let uniqueArr = [this[0]];
        this.sort((a,b) => {
            return a-b
        })
        for(let i = 1; i < this.length; i++){
            if(this[i]) !== this[i-1]){
                uniqueArr.push(this[i])
            }
            
        }
        return uniqueArr
    }

The first method and the third method uses the indexOf (), the function of the enforcement mechanism will traverse an array
second uses a hash table, is the fastest
fourth also has a computational complexity of sorting

Method five:

let a = new Array(1,2,3,4,4,3,5,6,5,7,7,8);
console.log([...new Set(a)]);

Guess you like

Origin www.cnblogs.com/sunidol/p/11515304.html