欢迎使用CSDN-markdown编辑器

来源:互联网 发布:网络歌手 十三电音 编辑:程序博客网 时间:2024/06/07 22:09

数组去重的几种方法

方法一

思想:创建一个新数组(结果数组),每次取原数组中的元素并检查结果数组中是否已经存在该元素,如果不存在,则将该元素加入该数组,否则,跳过该元素去检查下一个元素。

Array.prototype.unique1 = function(){   var result = [this[0]];   for(var i = 1; i < this.length; i++){    var repeat = false;    for(var j = 0; j < result.length; j++){     if(this[i] == result[j]){      repeat = true;      break;     }    }    if(!repeat){     result.push(this[i]);    }   }   return result;  };  

方法二

思想:
先将数组进行排序,这样数组中重复的元素会被排列到一起,检查在结果数组中是否已存在只需将该元素与结果数组的最后一个元素进行比较即可。和方法一相似,创建新的结果数组,将不重复的元素插入到结果数组中。

Array.prototype.unique2 = function(){  //先排序  this.sort();  var result = [];  result.push(this[0]);  for(var i = 1; i < this.length; i++){    if(this[i] != result[result.length-1]){      result.push(this[i]);    }  }  return result;};

方法三

思想:
利用一个对象来实现哈希表的思想,具体做法是每次取一个元素,到对象中去访问这个值,如果访问不到,则把该元素放入结果数组中,并把该元素值作为属性存入对象,赋值true。

Array.prototype.unique3 = function(){    var hash = {},        len = this.length,        result = [];    for(var i = 0; i < len; i++){      if(!hash[this[i]]){        hash[this[i]] = true;        result.push(this[i]);      }    }    return result;  };

如果数组中有字符串,使用以下代码

Array.prototype.unique3 = function(){    var hash = {},        len = this.length,        str = '',        result = [];    for(var i = 0; i < len; i++){      if(typeof this[i] == 'string'){        str = 'str_';      }else{        str = '';      }      if(!hash[str + this[i]]){        hash[str + this[i]] = true;        result.push(this[i]);      }    }    return result;  };  
0 0
原创粉丝点击