Home  >  Article  >  Web Front-end  >  Two common javascript array deduplication methods, ideas and codes_javascript skills

Two common javascript array deduplication methods, ideas and codes_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:39:15947browse

The first is a more conventional method
Ideas:
1. Construct a new array to store the results
2. Take one out of the original array each time in the for loop element, use indexOf to find whether the element exists in the new array
3. If not, store it in the result array

Copy code The code is as follows:

Array.prototype.unique1 = function(){
var res = [];
for(var i = 0; i < this.length; i ){
if(res.indexOf(this[i]) == -1){
res.push(this[i]);
}
}
return res;
}
var arr = [1, 'a', 'a', 'b', 'd', 'e', ​​'e', ​​1, 0]
alert(arr.unique1( ))

This basis can be slightly optimized, but the principle remains the same and the effect is not obvious
Copy code The code is as follows:

Array.prototype.unique1 = function(){
var res = [this[0]];//Directly change the first element in the original array Store in the new array constructed
for(var i = 1; i < this.length; i ){//The loop starts from the second element
if(res.indexOf(this[i]) == -1){
res.push(this[i]);
}
}
return res;
}
var arr = [1, 'a', 'a', 'b', 'd', 'e', ​​'e', ​​1, 0]
alert(arr.unique1())

Second The method is more efficient than the above method
Ideas:
1. Sort the original array first
2. Check whether the i-th element in the original array is the last element in the result array The same, because it has been sorted, the duplicate elements will be in adjacent positions
3. If they are not the same, the element will be stored in the result array
Copy code The code is as follows:

Array.prototype.unique2 = function(){
this.sort(); // Sort first
var res = [ this[0]];
for(var i = 1; i < this.length; i ){
if(this[i] !== res[res.length - 1]){
res.push(this[i]);
}
}
return res;
}
var arr = [1, 'a', 'a', 'b', 'd', 'e', ​​'e', ​​1, 0]
alert(arr.unique2())
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn