Here are 3 methods that are more common, and can be viewed as a downward, downward, performance higher.
The first is a more conventional approach, ideas are as follows:
1. Build a new array, and the new array is the same as the one that holds the result
Every time an element is taken from another array in the 2.for loop, the loop is compared with the result array.
3. If the element is not in the result array, it is stored in the result array
The code is as follows:
varARR1 = [1,2,3,4,5,6];varARR2 = [9,8,7,6,5,4];
vararr =Unitarray (ARR1,ARR2); alert (arr);functionUnitarray (ARRA,ARRB) {varARR3 =NewArray (); for(vari = 0; i < arra.length; i++) {Arr3.push (arra[i]); }; for(varj = 0; J < Arrb.length; J + + ){ varrepeat = 0; for(vark = 0; K < Arra.length; k++ ){ if(Arrb[j] = =Arra[k]) {Repeat= 1; }; }; if(Repeat = = 0) {Arr3.push (arrb[j]); }; }; returnArr3;};
the second method is more efficient than the above method. ideas are as follows:
1. First combine two arrays into a new array A1
2. Sort the new array (using the Sort function)
3. Create a new array A2, insert the A1 array first into the new array A2, and begin to read the elements in the A1 to compare with the last one in A2, if not, add A1
The code is as follows:
varARR1 = [1,2,3,4,5,6];varARR2 = [9,8,7,6,5,4];varArrA =Arr1.concat (ARR2); Arra.sort ();varARRB =NewArray (); Arrb.push (arra[0]);varLengtha =arra.length; for(vari = 0; i < Lengtha; i++ ){ varnum = arrb.length-1; if(Arrb[num]! = arra[0]) {Arrb.push (Arra.shift ()); }Else{arra.shift (); }};alert (ARRB);
The second method also has some limitations because it is sorted before going to heavy, so the final return of the de-weight result is also sorted. This method is not available if the order of the array is not changed to be heavy.
The third method (recommended). ideas are as follows:
1. Create a new array to hold the result
2. Create an empty object
3.for Loop, each time an element is taken out and compared to the object, if the element is not duplicated, it is stored in the result array, and the content of the element as an object property, and assigned a value of 1, deposited in the 2nd step of the object created.
Note: As for how to compare, it is to remove an element from the original array, and then go to the object to access the property, if you can access the value, then the description is repeated.
The code is as follows:
Array.prototype.unique =function(){ varres = []; varJSON = {}; for(vari = 0; I < This. length; i++){ if(!json[ This[i]]) {Res.push ( This[i]); json[ This[i]] = 1; } } returnRes;}vararr = [112,112, 34, ' Hello ', 112,112, 34, ' hello ', ' str ', ' str1 '];alert (Arr.unique ());
JS Array de-weight method