In a front-end interview I participated in yesterday, there was a question about deduplication of arrays. The first thing that came to mind was the method of storing key values in objects. The code is as follows
Method 1: (Simple key value storage)
Array.prototype.distinct1 = function() {
var i=0 ,tmp={},that=this.slice(0)
this.length=0;
for(;iif(!(that[i] in tmp)){
this[this.length]=that[i];
tmp[that[i]]=true;
}
}
return this;
} ;
The above method is not complicated and the idea is simple, but when it comes to different types that can be converted into the same string, it is over, such as 1 and "1"; so the traditional method is used again Double loop, the code is as follows
Method 2: (double loop)
Array.prototype.distinct2 = function() {
var i=0,flag,that=this.slice(0);
this.length=0;
for(;ivar tmp=that[i];
flag=true;
for(var j=0;jif(this[j]===tmp){flag=false;break}
}
if(flag)this[this.length]=tmp;
}
return this;
};
The above method got the desired result, but the two-layer loop efficiency is relatively low. Let’s find a way to start with the first method, and then add the characters String to save the type of array items. If there is a new type, connect the string and add it. When searching, if you find a saved type, replace the string of the saved type with empty. The code is as follows
Method 3 : (Save key value and type)
Array .prototype.distinct4 = function() {
var i=0,tmp={},t2,that=this.slice(0),one;
this.length=0;
for(; ione=that[i];
t2=typeof one;
if(!(one in tmp)){
this[this.length]= one;
tmp[one]=t2;
}else if(tmp[one].indexOf(t2)==-1){
this[this.length]=one;
tmp [one] =t2;
}
}
return this;
};
In order to distinguish the efficiency gap between various algorithms for different data, several To verify with an extreme example, first look at the situation where all array items from 1 to 80 are different and looped 1000 times. Well, IE6 is weak
IE9:Chrome:
Firefox: IE6:
The following is the situation where all 80 items are repeated 1000 times. Based on the above data, it is found that except The double loop performance of IE6-8 and other browsers is good, but the double loop of IE6-8 is about 10-20 times slower, which is sad. If your website only supports IE9 or above, you can rest assured to use the double loop method. Otherwise, you should still use the key value method. Choose method one or method three according to the data situation (method four in the picture, I found out that it was too late to change the picture. , the original method three was to use Array’s indexOf, but it was not released because it was slow and incompatible)
IE9: Chrome:
Firefox: IE6: