Several methods of JS array de-weight

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.