easy remove duplicat objects inside arrays code example
Example 1: Removing duplicates in an Array of Objects
const seen = new Set();
const arr = [
{ id: 1, name: "test1" },
{ id: 2, name: "test2" },
{ id: 2, name: "test3" },
{ id: 3, name: "test4" },
{ id: 4, name: "test5" },
{ id: 5, name: "test6" },
{ id: 5, name: "test7" },
{ id: 6, name: "test8" }
];
const filteredArr = arr.filter(el => {
const duplicate = seen.has(el.id);
seen.add(el.id);
return !duplicate;
});
Example 2: remove duplicate in aaray of objects
const things = {
thing: [
{ place: 'here', name: 'stuff' },
{ place: 'there', name: 'morestuff1' },
{ place: 'there', name: 'morestuff2' },
],
};
const removeDuplicates = (array, key) => {
return array.reduce((arr, item) => {
const removed = arr.filter(i => i[key] !== item[key]);
return [...removed, item];
}, []);
};
console.log(removeDuplicates(things.thing, 'place'));