DEV Community

Discussion on: Removing duplicates in an Array of Objects in JS with Sets

Collapse
 
mayanxoni profile image
Mayank Soni

Hi Tony. Your answer helped me, thanks!
BTW, can you please help me achieve this array?
[
{ id: 1, name: "test1" },
{ id: 2, name: "test2" },
{ id: 2, name: "test3" },
{ id: 3, name: "test2" }
]

I mean even if 'id' or 'name' already exists, it should not be omitted because either of the value is different (like in the case of 'name: "test2"') in the whole array.

Collapse
 
programmist profile image
Tony Childs

Hi Mayank,

I'm not sure I follow. If no duplicates are removed then that is just the original array is it not? Or do you mean you want an array with just ids 1, 2, and 3? If so, you can use Array.prototype.filter and only return true for the ids you want to keep.

Collapse
 
imcorfitz profile image
Corfitz

Hey @mayanxoni ,

Might be late with a reply here, but in your case I would probably map through your array of objects as stringified content, as you are not relying on a single identifier but an entire object.

NB: Though this might not be performant when you are dealing with bigger objects and large arrays.

const arr = [
{ id: 1, name: "test1" },
{ id: 2, name: "test2" },
{ id: 2, name: "test2" },
{ id: 2, name: "test2" },
{ id: 2, name: "test3" },
{ id: 3, name: "test2" }
];

const newArray = Array.from(new Set(arr.map(el => JSON.stringify(el)))).map(el => JSON.parse(el));
Enter fullscreen mode Exit fullscreen mode