让前端飞前端Web前端之路

JavaScript数组去重方法合集

2018-07-26  本文已影响16人  码代码的青年

一、函数

方法一:先进行原数组升序排序,然后对比相邻元素

Array.prototype.distinct1 = function () {
    var time = new Date().getTime();       //测试性能的相关代码
    var temp = this.sort(function (a, b) {
        return a-b;
    });
    var res = [temp[0]];
    for(var i=0; i<temp.length;i++){
        if(temp[i] !== res[res.length-1]){
            res.push(temp[i]);
        }
    }
    console.log(res, new Date().getTime()-time);
};

方法二:利用对象属性唯一性

Array.prototype.distinct2 = function () {
    var time = new Date().getTime();       //测试性能的相关代码
    var res=[],obj={};
    for(var i=0; i<this.length;i++){
        if(!obj[this[i]]){
            res.push(this[i]);
            obj[this[i]]=1;
        }
    }
    console.log(res, new Date().getTime()-time);
};

方法三:利用数组indexOf方法

Array.prototype.distinct3 = function () {
    var time = new Date().getTime();       //测试性能的相关代码
    var res=[];
    for(var i=0; i<this.length;i++){
        if(res.indexOf(this[i])===-1){
            res.push(this[i]);
        }
    }
    console.log(res, new Date().getTime()-time);
};

方法四:利用数组includes方法

Array.prototype.distinct4 = function () {
    var time = new Date().getTime();       //测试性能的相关代码
    var res=[];
    for(var i=0; i<this.length;i++){
        if(!res.includes(this[i])){
            res.push(this[i]);
        }
    }
    console.log(res, new Date().getTime()-time);
};

方法五:利用数组forEach、includes方法

Array.prototype.distinct5 = function () {
    var time = new Date().getTime();
    var res=[];
    this.forEach(function (value) {
        if(!res.includes(value)){
            res.push(value);
        }
    });
    console.log(res, new Date().getTime()-time);
};

方法六:利用ES6 Set方法

Array.prototype.distinct6 = function () {
    var time = new Date().getTime();       //测试性能的相关代码
    console.log(Array.from(new Set(this)), new Date().getTime()-time);
};

二、性能

var data = [];
for(var j=0;j<1000000;j++){
    data.push(Math.round(Math.random()*15));
}
data.distinct1(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  221ms
data.distinct2(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  5ms
data.distinct3(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  19ms
data.distinct4(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  20ms
data.distinct5(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  44ms
data.distinct6(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  77ms

二、总结

1、对比方法四、方法五,可知尽量少用forEach,而应该用for循环代替。
2、对比运行时间,方法二所需时间最短,性能最优。
3、有其他好的方法,欢迎大家在底下留言,我会补上去的。


广告:微信搜索关注公众号【休闲小达人】,零投资 -- 在家赚零花钱。


上一篇下一篇

猜你喜欢

热点阅读