snippetjavascriptCritical
How can I remove all duplicates from an array of objects?
Viewed 0 times
arrayhowfromremoveobjectsduplicatescanall
Problem
I have an object that contains an array of objects.
What is the best method to remove duplicate objects from an array? So, for example,
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.