对前端数组去重方法的一些总结

121 阅读1分钟

1.利用数组的indexOf方法进行去重

1.1 对索引的判断,只留下第一次出现的项

var array = [1, '1', 3, 5, 77, 88, 43]
Array.prototype.unique = function(){
    return this.filter((item, index) => {
        return this.indexOf(item) == index
   })
}

1.2 放入新的数组之中

   1.利用数组的indexOf方法进行去重                var dulicateArray = function(arr){            var newArray = []                  arr.forEach(item => {                          if(newArray.indexOf(item) === -1){                    newArray.push(item)                }            });            return newArray        }        var newarr = dulicateArray(array)

2. 双循环方法去重

 2. 数组的双重循环去重        Array.prototype.unique = function(){            const newArray = []            let isRepeat;            for(let i = 0; i < this.length; i++){                isRepeat = false                for(let j = 0; j< newArray.length; j ++){                    if(this[i] === newArray[j]){                        isRepeat = true                        break                    }                }                if(!isRepeat){                    newArray.push(this[i])                }            }            return newArray        }        console.log(array.unique())        算法可以适当改进减少运算量        Array.prototype.uinque = function(){            var newArray = []            let isRepeat            for(i = 0; i<this.length; i++){                isRepeat = false                for(j = i + 1; j< this.length; j++){                    if(this[i] === this[j]){                        isRepeat = true                    }                }                if(!isRepeat){                    newArray.push(this[i])                }            }            return newArray        }        console.log(array.uinque())