数组去重方法

找了几个数组去重的方法

1.利用hash表 (效率最高,推荐)

 1     Array.prototype.unique = function () {
 2         var json = {}, res = [];
 3         for(var i = 0; i < this.length;i++) {
 4             if (!json[this[i]]) {
 5                 json[this[i]] = true;  // 存入hash表
 6                 res.push( this[i] );
 7 
 8             }
 9         }
10         return res;
11     };

原理就是利用了对象的key的唯一性,这也是目前最好的方法

 

2. 第二种常规方法

 1     Array.prototype.unique = function () {
 2         var res = [this[0]];
 3         for (var i = 1; i < this.length; i++) {
 4             var repeat = false;
 5             for (var j = 0; j < res.length; j++) {
 6                 if (this[i] == res[j]) {
 7                     repeat = true;
 8                     break;
 9                 }
10             }
11             if (!repeat){
12                 res.push(this[i]);
13             }
14         }
15         return res;
16     };

 

3.第三种 利用数组的indexOf

 1     Array.prototype.unique = function () {
 2         var res = [];
 3         for(var i = 0; i < this.length; i++ ){
 4 //            如果当前已经报错过,跳过
 5 //            否则push
 6             if ( res.indexOf(this[i]) == -1 ) {
 7                 res.push(this[i]);
 8             }
 9         }
10         return res;
11     };

 

posted @ 2016-11-03 10:12  李二leon  阅读(144)  评论(0编辑  收藏  举报