数组去重的几种方法

  最近看了很多数组去重的方法,现在把他们总结一下,收集了4种方法各有差异,代码如下:

  1.   数组的indexOf方法,但是IE6-8并不支持数组的这个方法。
     1 function unique(arr) {  
     2     var ret = []
     3       for (var i = 0; i < arr.length; i++) {    
     4          var item = arr[i]
     5             if (ret.indexOf(item) === -1) {
     6            ret.push(item)   
     7            }  
     8  9         return ret
    10     }
    11     //IE6-8不支持数组的indexOf方法,可以区别字符类的相同数字
    12     console.log(unique([1,'2',3,4,2,3,5,1,8,9,5]));
    13     //1,'2',3,4,2,5,8,9

     

  2. 双重循环的查找方法,但是性能不高
     1 Array.prototype.distinct2 = function() { 
     2     var i = 0,
     3         flag, that = this.slice(0);
     4     this.length = 0;
     5     for (; i < that.length; i++) {
     6         var tmp = that[i];
     7         flag = true;
     8 
     9         for (var j = 0; j < this.length; j++) {
    10             if (this[j] === tmp) {
    11                 flag = false;
    12                 break
    13             }
    14         }
    15         if (flag) this[this.length] = tmp;
    16     }
    17 
    18 
    19 return this; 
    20 }; 
    21 console.log([1,2,3,2,4,3,'2',1].distinct2());
    22 //1,2,3,4,'2'

     

  3. hash表的方法
     1 Array.prototype.unique = function() {
     2         var ret = [];
     3         var hash = {};
     4         var len = this.length;
     5         for (var i = 0; i < len; i++) {
     6 
     7             var key = this[i];
     8             if (!hash[key]) {
     9                 hash[key] = true;
    10                 ret.push(key)
    11             }
    12         }
    13         return ret;
    14     };
    15     console.log([1, '1', 2, 3, 3, 4].unique());
    16     //1,2,3,4

     

  4. 上面的hash表方法并不能区分字符类型的相同数字,所以加了一个typeof方法来区别字符类的数字
     1 Array.prototype.unique = function () {
     2      var ret = [];
     3      var hash = {} ;
     4      for (var i = 0; i <this.length; i++) { 
     5           var item =this[i];
     6           var key = typeof(item) + item ;
     7           if (hash[key] !== 1) {     
     8                  ret.push(item) ;
     9                   hash[key] = 1  ;
    10       }  
    11     }  
    12     return ret;
    13     }
    14     console.log([1,'1',2,3,3,2,4,1].unique());
    15     //1,'1',2,3,4
    16      //可以区别字符‘1’和数字1

     

 

posted @ 2014-04-15 18:26  Jing.w  阅读(206)  评论(0编辑  收藏  举报