Search code examples
javascriptarraysobjectduplicates

How to remove all duplicates from an array of objects?


I have an object that contains an array of objects.

obj = {};

obj.arr = new Array();

obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});

I'm wondering what is the best method to remove duplicate objects from an array. So for example, obj.arr would become...

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}

Solution

  • A primitive method would be:

    const obj = {};
    
    for (let i = 0, len = things.thing.length; i < len; i++) {
      obj[things.thing[i]['place']] = things.thing[i];
    }
    
    things.thing = new Array();
    
     for (const key in obj) { 
       things.thing.push(obj[key]);
    }