Home  >  Article  >  Web Front-end  >  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:331498browse

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.

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

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