Array de-weight, front-end interview loves the problem, the problem is simple and can see a programmer to the computer program implementation process of understanding how.
There are a lot of ways to get an array, which is the ideal one, I'm not sure. So I tested the efficiency of the next array de-weight. Test 200,000 data and experience it more efficiently as the data becomes more efficient.
Here are my three high-efficiency methods for online summary and efficiency testing, do not like to spray O (∩_∩) o~~
Array de-weight Method 1:
1Array.prototype.unique1 =function(){2Console.time ("Array de-weight Method 1");//Recordtime to start execution3 vararr = [];//Create a temporary array4 varobj = {};//Create an empty object5 for(vari = 0; I < This. length; i++) {//iterate over the current array to be de-iterated6 if(!obj[ This[i]]) {//determines whether the current item is present in the Obj object and does not execute7Arr.push ( This[i]);//Push the current item to the temporary array8obj[ This[i]] = 1;//save current item to obj object9 }Ten } OneConsole.timeend ("Array de-weight Method 1");//Recordtime to end execution A returnarr; -}
Array de-weight Method 2:
1Array.prototype.unique2 =function(){2Console.time ("Array de-weight Method 2");//Recordtime to start execution3 vararr = [];//Create a temporary array4 for(vari = 0; I < This. length; i++) {//iterate over the current array to be de-iterated5 if(Arr.indexof ( This[i]) = =-1) {//determines whether the current item is present in the temporary array and does not execute6Arr.push ( This[i]);//Push the current item to the temporary array7 }8 }9Console.timeend ("Array de-weight Method 2");//Recordtime to end executionTen returnarr; One}
Array de-weight Method 3:
1Array.prototype.unique3 =function(){2Console.time ("Array de-weight Method 3");//record when the execution started3 vararr = [ This[0]];//creates a temporary array and will go to the first item of the redo array into a temporary array4 for(vari = 1; I < This. length; i++) {//start traversing from the second item to go to the heavy array5 if( This. IndexOf ( This[i]) = = i) {//determines whether the current item is present in the temporary array and does not execute6Arr.push ( This[i]);//Push the current item to the temporary array7 }8 }9Console.timeend ("Array de-weight Method 3");//record when the execution endedTen returnarr; One}
Efficiency test Method:
1 varARR1 = [];//create an array to go to the heavy2 for(vari = 0; I < 200000; i++) {//traversal of 200,000 data3Arr1.push (parseint (Math.random () * 10) + 1);//return all data to a random number (1-10) and push to the array to be removed4 }5 6Console.log (Arr1.unique1 ());//Print array de-weight Method 1 Execution Time7Console.log (Arr1.unique2 ());//Print array de-weight Method 2 Execution Time8Console.log (Arr1.unique3 ());//Print array de-weight method 3 Execution Time
Efficiency test Results:
(End ~ ~)
JavaScript array de-weight-efficiency test