In the process of writing programs, we often encounter the need to remove duplicate elements from an array. It is actually not difficult to implement this function.
We can use a double loop to achieve this. For small arrays, there is certainly nothing wrong with doing so.
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> <br>function unique(data) { <br>data = data || []; <br>var a = {}; <br>for (var i=0; i<data.length; i ) { <BR>var v = data[i] ; <BR>if (typeof(a[v]) == 'undefined'){ <BR>a[v] = 1; <BR>} <BR>}; <BR>data.length=0; <BR>for (var i in a){ <BR>data[data.length] = i; <BR>} <BR>return data; <BR>} <BR>function test(){ <BR>var arr = [ 9,1,3,8,7,7,6,6,5,7,8,8,7,4,3,1]; <BR>var arr1 = unique(arr); <BR>alert(arr1 .join(",")); <BR>} <BR>test(); <BR></script>
Output result:
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;ifor(var j=i 1;jif(this[i]===this[j]){
j = i;
}
}
newArray.push(this[i]);
}
return newArray;
}
But it’s obvious There is a for loop embedded in another for loop, which must be very time-consuming when dealing with 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 ; The value is used as the key value of the provisionalTable object. If the corresponding value does not exist, the value of this array is pushed to the new array.
The efficiency has been improved, but there is a bug. It is assumed that convertible numbers and strings are used in the array. For example, one of the arrays [6, "6"] will be removed at this time. Tragedy and looking for a solution.
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