1Array.prototype.unique1 =function () {2 varn = [];//a new temporary array3 for(vari = 0; I < This. length; i++)//iterate through the current array4 {5 //if the current array of I has been saved into a temporary array, then skip,6 //Otherwise push the current item to the temporary array7 if(N.indexof ( This[i]) = =-1) n.push ( This[i]);8 }9 returnN;Ten }; One A -Array.prototype.unique2 =function() - { the varn = {},r=[];//n is a hash table and r is a temporary array - for(vari = 0; I < This. length; i++)//iterate through the current array - { - if(!n[ This[i]])//If there is no current item in the hash table + { -n[ This[i]] =true;//Deposit Hash Table +R.push ( This[i]);//Push the current item of the current array into the temporary array A } at } - returnR; - }; - - -Array.prototype.unique3 =function() in { - varn = [ This[0]];//result Array to for(vari = 1; I < This. length; i++)//start traversing from the second item + { - //if the item I of the current array first appears in the current array, the position is not I, the //then it means that item I is repeated and ignored. Otherwise, the result array is stored * if( This. IndexOf ( This[i]) = = i) N.push ( This[i]); $ }Panax Notoginseng returnN; - }; the + AArray.prototype.unique4 =function() the { + This. Sort (); - varre=[ This[0]]; $ for(vari = 1; I < This. length; i++) $ { - if( This[i]!== re[re.length-1]) - { theRe.push ( This[i]); - }Wuyi } the returnre; - }; Wu - About vararr = [1,2,2,2,3,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]
Several methods of JS array de-weight