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
1496 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.

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
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!