DEV Community

Discussion on: What is the best solution for removing duplicate Objects from an Array?

Collapse
 
webreflection profile image
Andrea Giammarchi • Edited

You could also combine both solutions.

const by = property => function (object) {
  const value = object[property];
  return !(this.has(value) || !this.add(value));
};

const myFitleredArr = myArr.filter(by('name'), new Set);

This way you could reuse over and over the given Set, but you could also make it a one-shot each time.

const by = key => {
  const set = new Set;
  return obj => !(set.has(obj[key]) || !set.add(obj[key]));
};
Collapse
 
pixari profile image
Raffaele Pizzari

Done :)

Collapse
 
webreflection profile image
Andrea Giammarchi

Thanks, but there is a typo apptets instead of accepts, and I think you should explain the one-off approach too, where you don't need to pass any Set.

Passing new Set is not super handy if you never reuse that Set, so that in such case not passing a second argument to filter(...) provides a better UX.

Thread Thread
 
pixari profile image
Raffaele Pizzari

Thanks again, Andrea!

Collapse
 
pixari profile image
Raffaele Pizzari

This is a very good hint.
I'll edit soon the post adding this solution with some explanations.

Thank you, Andrea!