This paper describes three kinds of JS de-weight method
The first method of thinking:
1. Build a new array to store the results
Each time a 2.for loop takes an element from the original array to see if the element is in the result array
3. If the element is not in the result array, it is stored in the result array, otherwise it jumps into the next loop. The code is as follows:
1Array.prototype.unique =function(){2 varres = [ This[0]];3 for(vari = 1; I < This. length; i++){4 if(Res.indexof ( This[i]) >=0){5 Continue ;6}Else{7Res.push ( This[i]);8 }9 }Ten returnRes; One } A vararr = [1, ' A ', ' a ', ' B ', ' d ', ' e ', ' e ', 1, 0] -Console.log (Arr.unique ());
The second way of thinking:
1. Sort the original array first
2. Check that the first element in the original array is the same as the last element in the result array, because it is already sorted, so the repeating element is in the adjacent position
3. If it is not the same, the element is stored in the result array
1Array.prototype.unique =function(){2 This. sort ();//Sort First3 varres = [ This[0]];4 for(vari = 1; I < This. length; i++){5 if( This[i]!== res[res.length-1]){6Res.push ( This[i]);7 }8 }9 returnRes;Ten } One vararr = [1, ' A ', ' a ', ' B ', ' d ', ' e ', ' e ', 1, 0]; AConsole.log (Arr.unique ());
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 of thinking:
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.
1Array.prototype.unique =function(){2 varres = [];3 varJSON = {};4 for(vari = 0; I < This. length; i++){5 if(!json[ This[i]]) {6Res.push ( This[i]);7json[ This[i]] = 1;8 }9 }Ten returnRes; One } A vararr = [1, ' A ', ' a ', ' B ', ' d ', ' e ', ' e ', 1, 0];
-Console.log (Arr.unique ());
Specific use of which method, specific to the West specific analysis bar.
JS Array to weigh three ways