Array deduplication is a common requirement. we will temporarily consider repeated arrays of the same type. It mainly aims to clarify the ideas and consider the performance. The following methods are available on the internet. here is a brief summary. Summary of deduplication methods for javascript arrays
Array. prototype. unique1 = function () {var n = []; // A new temporary array for (var I = 0; I <this. length; I ++) // traverse the current array {// skip this step if the I of the current array has been saved as a temporary array, // otherwise, 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, and r is a temporary array for (var I = 0; I <this. length; I ++) // traverses the current array {if (! N [this [I]) // if the hash table does not have the current item {n [this [I] = true; // save it to the 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 ++) // traverse from the second entry {// if the position where the I entry of the current array appears for the first time in the current array is not I, // This indicates that the I-th item is repeated and ignored. Otherwise, store 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, 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]
The indexOf method of the array is used in both the 1st and 3rd methods. The purpose of this method is to find the location where the saved parameter appears for the first time in the array. Obviously, the js engine will traverse the array when implementing this method until it finds the target. Therefore, this function will waste a lot of time. The method in 2nd uses the hash table. Store existing objects in the form of a subobject. The reference of the underlying object is much faster than the search for an array using indexOf.
The fourth method is to first sort the array and then compare the adjacent values. The JS native sort method is used for sorting. the JS engine should use quick sorting internally. The final test result is that the average running time of this method is about three times that of the second method, but it is much faster than the first and third methods.
The above is all the content of this article. I hope you will like it.