When writing a program, you often need to remove repeated elements from the array. It is not difficult to implement this function.
We can implement it with a two-repeating loop. For small arrays, this is certainly not inappropriate.
However, if our array is large, there are tens of thousands of elements in it. The efficiency is extremely low when two duplicates are used.
Next we will use js features to compile an efficient method for removing repeated elements from arrays.
Copy codeThe Code is as follows:
<Script>
Function unique (data ){
Data = data | [];
Var a = {};
For (var I = 0; I <data. length; I ++ ){
Var v = data [I];
If (typeof (a [v]) = 'undefined '){
A [v] = 1;
}
};
Data. length = 0;
For (var I in ){
Data [data. length] = I;
}
Return data;
}
Function test (){
Var arr = [9, 1, 3, 8, 7, 6, 6, 5, 7, 8, 7, 4, 3, 1];
Var arr1 = unique (arr );
Alert (arr1.join (","));
}
Test ();
</Script>
Output result:
9, 1, 3, 8, 7, 6, 5, 4
Deduplication of the js array removes the repeated elements in the array:
Copy codeThe Code is as follows:
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;
}
However, it is obvious that the for loop is embedded with another for loop. It must be time-consuming for a large amount of data! Inefficient! A new method has been optimized through search and expert guidance:
Copy codeThe Code is as follows:
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;
}
A temporary provisionalTable object is used to take the value of the array 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.
Efficiency is improved, but there is a bug, That is, assuming that the array is replaced with convertible numbers and strings, such as the array [6, "6"], then it will be removed. Tragedy, while seeking a solution.