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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function removeDuplicateObjectsFromArray(array, property) { | |
const set = new Set(array.map(el => el[property])); | |
return array.filter(el => set.delete(el[property])); | |
} |