JavaScript contains an array of objects to remove weight

Source: Internet
Author: User

Array.prototype.clearRepeat =function(){  varresult =[], obj= {};  for(vari = 0; I < This. length; i++){     if(typeof( This[i] = = = = "Object"){        varobjname = "Object:";  for(varXinch  This[i]) {objname+=x; ObjName+= This[i][x]; }        if(!Obj[objname]) {Obj[objname]= "New"; Result.push ( This[i]); }    }    Else if(!obj[typeof( This[i]) + This[i]]) {Result.push ( This[i]); obj[typeof( This[i]) + This[i]] = "new"; }  }  returnResult;}

Main ideas:
Using the Obj object to mark the stored array element, when obj does not contain the element at this time, push the element into the result array and mark the element in the Obj object;

Places to be aware of:
Ordinary elements can be stored directly in obj as follows: object Type + Object value , which guarantees the uniqueness of the elements and can be correctly used when the elements are "5" and 5 .
Revenue, when this element is an object, if you still store obj in this way, then you get the "Object[object object" and you can't distinguish whether the object is equal, so this
The properties and values in the object are traversed and treated as objname as the property names in obj, so that obj[objname] is used to differentiate whether each object is equal.
To test an array:
var test = [{2: "A", A: "AA"}, {2: "A", A: "AA"}, {ab: "A", A: "AA"}, {}, {}, 1,1,2, ' 2 ', ' 2 ', 3,4,5,{},{2: "A", A: "AA"}]
Test results:

JavaScript contains an array of objects to remove 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.