JS array deduplication
JS array deduplication
Javascript
20:31:31 read 345
Comment 0 font size: large, medium, and small subscriptions
Deduplication of the js array removes the repeated 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;
} But 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:
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;
} 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 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.