JavaScript Array to Redo method rollup
An array to repeat is a common requirement, and we temporarily consider the same type of array to repeat. The main reason is to clear the thinking and consider the performance. The following methods, the basic online have, here is simply summed up.
JavaScript array to Redo method rollup
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 This is the |
Array.prototype.unique1 = function () {var n = [];//A new temporary array for (var i = 0; i < this.length; i++)//traverse the current array {//IF The first array has been saved in the temporary array, so 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++)//traverse the current 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]);//Push the current item of the current array to the temporary array} 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 an item in the current array in the current array is not I,//so that the item I is repeating is 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.