公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

1、利用 indexOf() 方法之一

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

2、利用 indexOf() 方法之二

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

3、优化遍历数组法

Array.prototype.unique = function(){
 var hash=[];
 // 双层循环,外循环表示从 0 到 arr.length
 for (var i = 0; i < this.length; i++) {
 // 内循环表示从 i+1 到 arr.length
 for (var j = i+1; j < this.length; j++) {
 if(this[i]===this[j]){
 // 检测到有重复值时终止当前循环同时进入外层循环的下一轮判断
 ++i;
 }
 }
 // 将没重复的右边值放入新数组
 hash.push(this[i]);
 }
 return hash;
}

4、排序后再进行数组去重

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

5、利用数组 filter 方法过滤

Array.prototype.unique = function unique() {
 var res = this.filter(function(item, index, array) {
 return array.indexOf(item) === index;
 });
 
 return res;
}

6、利用对象属性的唯一性

Array.prototype.unique = function(){
 var temp = [],hash = {}; // hash 作为哈希表
 for (var i = 0;i < this.length;i++){
 if(!hash[ this[i] ]){ // 如果哈希表中没有当前项
 hash[ this[i] ] = true;
 temp.push(this[i])
 }
 }
 return temp;
}

7、利用 ES6 set 数据结构

Array.prototype.unique = function(){
 return Array.from(new Set(this));
}

上述七种方法中,经测试(测试数组元素个数从 1 万个- 1000 万个),代码运行速度从上到下依次降低,其中方法 1 和方法 2 速度差异不大,速度最慢,方法 3 的具体运行速度和数组具体情况相关,方法 4 速度比方法 1,2,3 快,但比方法 5,6,7 慢得比较多,方法 5,6,7 运行速度最快,且运行速度差异不大,不过鉴于 set 是 ES6 新加内容,在实际开发环境中,推荐使用稳定性和速度都比较不错的方法 5 和方法 6 。

拓展:若重复,则去掉该元素

function unique(arr){
 var hash=[];
 for (var i = 0; i < arr.length; i++) {
 if(arr.indexOf(arr[i])==arr.lastIndexOf(arr[i])){
 hash.push(arr[i]);
 }
 }
 return hash;
}

分享到:
标签:数组 JS
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定