How To Get Rid Of Duplicate Objects In An Array

There might be a better way to do this, but I found it to be a pretty straightforward method.

If you have an array of objects where some objects are duplicates, you can create a Set based on the property you want to use as a filter and then you can use the filter method over the original array, to only return the object if the property in question is still in the Set. If there’s a match, you want to make sure to remove that property from the Set so the duplicated Object doesn’t match with anything in the Set.

Here’s an example:

const arrayWithDuplicates = [
  {
    name: 'Dexter',
    age: 10,
  },
  {
    name: 'Alto',
    age: 12,
  },
  {
    name: 'Dexter',
    age: 10,
  },
];

const uniqueNames = new Set(arrayWithDuplicates.map((dog) => dog.name));

const filteredArray = arrayWithDuplicates.filter((dog) => {
  if (uniqueNames.has(dog.name)) {
    uniqueNames.delete(dog.name);
    return true;
  }
  return false;
});

Here is a refactored version that you can use: