0

I have created one array of object, and I want to insert Unique objects. var a=[];

a.push(new Number(11));
a.push({aa:"asdf",bb:"sadf"}
a.push({aa:"asdf",bb:"sadf"}

JSON.stringify(a)
"[11,{"aa":"asdf","bb":"sadf"},{"aa":"asdf","bb":"sadf"}]"

I want result like

JSON.stringify(a)
"[11,{"aa":"asdf","bb":"sadf"}]"
nirav dhanorkar
  • 185
  • 2
  • 9
  • For reference : http://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript – Stephan Sep 14 '16 at 12:14
  • Possible duplicate of [Remove Duplicates from JavaScript Array](http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array) – ljedrz Sep 14 '16 at 14:47

1 Answers1

0

var uniqueArray=[] is your resultArray. Array.indexOf is used to find whether the element already exist in the uniqueArray, if not simply push to uniqueArray, otherwise its a duplicate no need to push, resultant will be uniqueArray:

var uniqueArray=[];  //result array of contains duplicate free elements
for(var i=0;i<a.length;i++){
  //to check for duplication in the result array
   if(uniqueArray.indexOf(a[i])<0)
      uniqueArray.push(a[i]);
}

return uniqueArray;
J. Chomel
  • 8,193
  • 15
  • 41
  • 69
  • Please add some explanation for your code, so the OP can understand it. – beerwin Sep 14 '16 at 13:03
  • var uniqueArray=[]; is your resultArray. Array.indexOf is used to find whether the element already exist in the uniqueArray, if not simply push to uniqueArray, otherwise its a duplicate no need to push, resultant will be uniqueArray @beerwin – MAREESKANNNAN RAJENDRAN Sep 15 '16 at 03:58