JavaScript数组去重方法合集

作者 : 开心源码 本文共1929个字,预计阅读时间需要5分钟 发布时间: 2022-05-12 共365人阅读

一、函数

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

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 ]  221msdata.distinct2(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  5msdata.distinct3(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  19msdata.distinct4(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  20msdata.distinct5(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  44msdata.distinct6(); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]  77ms

二、总结

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


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


说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » JavaScript数组去重方法合集

发表回复