Home > Web Front-end > JS Tutorial > body text

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

伊谢尔伦
Release: 2017-07-24 13:27:33
Original
1654 people have browsed it

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>
Copy after login

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; 
}
Copy after login

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; 
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!