Home >Web Front-end >JS Tutorial >Detailed explanation of ideas and code examples on how to remove duplicate elements from an array in JavaScript

Detailed explanation of ideas and code examples on how to remove duplicate elements from an array in JavaScript

伊谢尔伦
伊谢尔伦Original
2017-07-24 13:27:331720browse

In the process of writing programs, we often encounter the need to remove duplicate elements from an array. We can use a double loop to achieve this, for small arrays. But if our array is relatively large, there are tens of thousands of elements in it. Then using double circulation is extremely inefficient. Below we will use the features of js to write an efficient method for removing duplicate elements from an array.

<script> 
function unique(data){ 
data = data || []; 
var a = {}; 
for (var i=0; i<data.length; i++) { 
var v = data[i]; 
if (typeof(a[v]) == &#39;undefined&#39;){ 
a[v] = 1; 
} 
}; 
data.length=0; 
for (var i in a){ 
data[data.length] = i; 
} 
return data; 
} 
function test(){ 
var arr = [9,1,3,8,7,7,6,6,5,7,8,8,7,4,3,1]; 
var arr1 = unique(arr); 
alert(arr1.join(",")); 
} 
test(); 
</script>

Output results:
9,1,3,8,7,6,5,4
js array deduplication is to remove duplicate elements in the array:

Array.prototype.delRepeat=function(){ 
var newArray=new Array(); 
var len=this.length; 
for (var i=0;i<len ;i++){ 
for(var j=i+1;j<len;j++){ 
if(this[i]===this[j]){ 
j=++i; 
} 
} 
newArray.push(this[i]); 
} 
return newArray; 
}

But it is obvious that there is a for loop embedded with another for loop, which must be very time-consuming under large amounts of data! Inefficient! After searching and expert advice, a new method has been optimized:

Array.prototype.delRepeat=function(){ 
var newArray=[]; 
var provisionalTable = {}; 
for (var i = 0, item; (item= this[i]) != null; i++) { 
if (!provisionalTable[item]) { 
newArray.push(item); 
provisionalTable[item] = true; 
} 
} 
return newArray; 
}

It is to use a temporary provisionalTable object and use the value of the array as the key value of the provisionalTable object. If the corresponding value does not exist, push the value of this array to a new array.

The above is the detailed content of Detailed explanation of ideas and code examples on how to remove duplicate elements from an array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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