HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How can I remove all duplicates from an array of objects?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayhowfromremoveobjectsduplicatescanall

Problem

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"});


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]);
}

Code Snippets

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]);
}

Context

Stack Overflow Q#2218999, score: 203

Revisions (0)

No revisions yet.