Remove duplicate elements from an array in JavaScript

Source: Internet
Author: User
Tags object object

1<script type= "Text/javascript" >2     vararr = ["B", "A", "a", 2, 3, 3, 2, 1, 4, {}];3Array.prototype.unique =function(){4     varRET = [];5     varo = {};//This object here is actually a temporary container, in the following operation, each time from the array to take an element, and then determine whether the object with this element as the property name exists in the object6     //O, if this element is used for the first time (that is, there is no repetition), it certainly does not exist in the object o, so the next step is to assign a value to this property (the purpose is to make it a7     //a complete object with property name: "Property value", so that the next time a duplicate array element, which is the same property name, will not be added to the object again, and the final guarantee Ret.push (v)8     //The element that this operation puts into the new array is not duplicated)9     varLen = This. Length;Ten      for(vari=0; i<len; i++){ One         varv = This[i]; A         if(!O[v]) { -O[V] = "Hello,world";//assign a value, a placeholder, a number, a string can be - Ret.push (v); the         } -     } -     returnret; - }; + Document.writeln (Arr.unique ()); -</script>

Page display: B,a,2,3,1,4,[object Object]

Remove duplicate elements from an array in JavaScript

Related Article

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.