How to remove the duplicates of the JavaScript array. The problem seems simple, but in fact it's hidden. Not only to achieve this function, but also to see your computer program execution in-depth understanding.
I've come up with a total of three algorithms for this purpose:
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 is already insured Save in a temporary array, skip,//Otherwise push the current item into 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 the hash table does not have the current item {N[this[i]] = true;//hash Table R.push (this[i]);//Push the current item of the current array into the temporary array}}return R;
Array.prototype.unique3 = function () {var n = [this[0]];//result array for (var i = 1; i < this.length; i++)//start with the second entry {//if the current array The first occurrence of item I in the current array is not i,//so 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;}
The 1th and 3rd methods all use the IndexOf method of the array. The purpose of this method is to look for the first occurrence of the stored parameter in the array. Obviously, the JS engine will iterate through the array until the target is found by implementing this method. So this function will waste a lot of time. The 2nd method uses a hash table. Deposit an object in the form that has already appeared through the subscript. The reference to the subscript is much faster than searching the array with indexof.
To determine the efficiency of these three methods, I made a test program, generated an array of 10000-length random numbers, and then used several methods to test the execution time. The results show that the second method is much faster than the other two methods. However, the memory footprint should be the second method more, because a hash table. This is the so-called space change time. This is the test page, you can also go to see.
According to Daniel's idea, I wrote a fourth method:
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;}
The idea of this method is to sort the array first and then compare the adjacent two values. When sorting the JS native sort method, the JS engine should be used in a quick sort. The result of the final test is that this method runs for an average of about three times times the second method, but much faster than the first and third methods.
JS Array de-weight