Home >Web Front-end >JS Tutorial >What are the methods for deduplicating arrays?
Today I will simply write about js array deduplication. Here I have summarized three methods.
The first method:
First define a temporary array, and then traverse the current array. If the i-th element of the current array has been saved into the temporary array Then skip this element; otherwise add the current item to the temporary array.
The specific code is as follows:
var arr = [23,23,1,1,1235,123,123,1235,45,345,457,45245,234,2341,23] ;
Array.prototype.unique1 = function(){
var n = [];//Define a new temporary array
for(var i = 0; i
//If the i-th element of the current array has been saved into the temporary array, skip it;
//Otherwise, push the current item into the temporary array
if(n.indexOf(this[i])==-1){
n.push(this[i]);
}
}
return n;
}
The second method:
First construct a new array to store the results. If the i-th item of the current array is the first in the current array If the position that appears is not i, then it means that the i-th item is repeated, filter it out, otherwise it will be stored in the result array.
The specific code is as follows:
Array.prototype.unique2 = function(){
var n = [this[0]] ;//Result array
for (var i = 1; i
//Then it means that the i-th item is repeated, filter it out, otherwise it will be stored in the result array
if(this.indexOf(this[i])==i){
n.push(this[i ]);
}
}
return n;
}
The third method:
Create a temporary table first, A temporary array. If there is no current item in the temporary table, it is stored in the temporary table and the current item of the current array is added to the temporary array.
The specific code is as follows:
Array.prototype.unique3=function(){
var n = {},r=[];//n is Temporary table, r is a temporary array
//Traverse the current array
for (var i = 0; i < this.length; i++) {
if (!n[this[i]]) { //If there is no current item in the temporary table
n[this[i]]=true;//Save to the temporary table
r.push(this[i]);//Push the current item of the current array To the temporary array
}
}
return r;
}
The above is the detailed content of What are the methods for deduplicating arrays?. For more information, please follow other related articles on the PHP Chinese website!