JavaScript Array to Redo method rollup
Array.prototype.unique1 = function () {var n = [];//A new temporary array for (var i = 0; i < this.length; i++)//traverse the current array {/
/If the current array has been saved in the temporary array, skip,//or push the current item to the temporary array if (N.indexof (this[i]) = = 1) n.push (this[i));
} return N;
}; Array.prototype.unique2 = function () {var n = {},r=[];//n is a hash table, r is a temporary array for (var i = 0; i < this.length; i++)//traversal when Previous array {if (!n[this[i]])//If there is no current item {N[this[i] in the hash table = true;//Deposit Hash Table R.push (this[i]);//Send current item of current array Pu
SH to the temporary array inside} return R;
};
Array.prototype.unique3 = function () {var n = [this[0]];//result array for (var i = 1; i < this.length; i++)//Go through the second item {//If the first occurrence of the current array in the current array is not I,//It means that item I is duplicated and ignored.
Otherwise deposit the result array if (This.indexof (this[i]) = = i) N.push (this[i));
} return N;
};
Array.prototype.unique4 = function () {this.sort ();
var re=[this[0]];
for (var i = 1; i < this.length i++) {if (This[i]!== re[re.length-1]) {Re.push (this[i));
} return re;
}; var arr = [1,2,2,2,3,3,4,5]; Console.log (Arr.unique1 ()); [1, 2, 3, 4, 5] Console.log (Arr.unique2 ()); [1, 2, 3, 4, 5] Console.log (Arr.unique3 ()); [1, 2, 3, 4, 5] Console.log (Arr.unique4 ()); [1, 2, 3, 4, 5]
Both the 1th and 3rd methods use the IndexOf method of the array. The purpose of this method is to find the position where the parameter is stored for the first time in the array. It is obvious that the JS engine will iterate through the array when it implements this method until it finds the target. So this function will waste a lot of time. The 2nd method uses a hash table. To deposit an object in a form that has already appeared through the subscript. The subscript reference is much faster than searching the array with indexof.
The fourth approach is to sort the array first and then compare the adjacent two values. The sort time uses the JS native sort method, the JS engine interior should be uses the quick sort. The result of the final test is that this method runs about three times times the average of the second method, but much faster than the first and third methods.
The above mentioned is the entire content of this article, I hope you can enjoy.