DEV Community

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

Collapse
 
coachmatt_io profile image
Matt

Without getting into cryptic one-liners, there's a pretty straight forward linear time solution as well.


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;
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
spiritupbro profile image
spiritupbro

wow crazy matt
thanks for this

Collapse
 
marinamosti profile image
Marina Mosti

Hey Matt, nice solution! Yeah, all ways leads to Rome :)

Collapse
 
andreasvirkus profile image
ajv

Well... yes and no.

I feel it's important to distinguish that the OP-s solution loops over the whole array twice. I know there are times to make a trade-off between performance and readability, but I don't feel this needs to be one of those times :)

Collapse
 
johnfewell profile image
John Fewell

Great answer, thank you Matt!