Javascript removes deplicates in an array

 Below is a sample code: 
01Array.prototype.delRepeat=function(){
02    var newArray=new Array();
03    var len=this.length;
04    for (var i=0;i<len ;i++){
05        for(var j=i+1;j<len;j++){
06            if(this[i]===this[j]){
07                j=++i;
08            }
09        }
10        newArray.push(this[i]);
11    }
12    return newArray;
13}

Obviously, there are two 'for' in this code snippet, which makes it very inefficient. Here is a more efficient one: 
 
01Array.prototype.delRepeat=function(){
02    var newArray=[];
03    var provisionalTable = {};
04    for (var i = 0, item; (item= this[i]) != null; i++) {
05        if (!provisionalTable[item]) {
06            newArray.push(item);
07            provisionalTable[item] = true;
08        }
09    }
10    return newArray;
11}


0 comments

Popular Posts

无觅相关文章插件,迅速提升网站流量