js高效率数组去重

来源:互联网 发布:suse linux 宕机分析 编辑:程序博客网 时间:2024/04/30 00:44

为数组对象添加数组去重方法,并且返回删除的数组元素:

方法1:

Array.prototype.clearRedurance=function(){   var newArray=[],//         redurance=[],//         i,//         length;        this.sort(function(a,b){    return a>b ? 1:(a<b ? -1:0);});//数组先排序    newArray.push(this[0]);    for(i=0,length=this.length;i<length;i++){    if(newArray[newArray.length-1]!=this[i]){        newArray.push(this[i]);    }else{     redurance.push(this[i]);     this.splice(i,1);     i--;     length--;}   }  return redurance;}
算法事件复杂度为O(n)。


方法2:利用hash

Arrary.prototype.clearReduance=function(){   var ret=[],         i=0,//         length=this.length,         item,//         key,//         hash={};   for(;i<length;i++){       item=this[i];       key=typeof(item)+item;       if(hash[key]!=1){             ret.push(item);            hash[key]=1;         }else{           ret.push(this[i]);           this.splice(i,1);           i--;           length--;         }     }     return ret;     }





2 0