Borislav Hadzhiev
Wed Oct 13 2021·3 min read
Photo by Jordan Whitfield
To remove all duplicate objects from an array:
filter()
method, passing it a function.const arr = [ {id: 1, name: 'Tom'}, {id: 1, name: 'Tom'}, {id: 2, name: 'Nick'}, {id: 2, name: 'Nick'}, ]; const uniqueIds = []; const unique = arr.filter(element => { const isDuplicate = uniqueIds.includes(element.id); if (!isDuplicate) { uniqueIds.push(element.id); return true; } return false; }); // 👇️ [{id: 1, name: 'Tom'}, {id: 2, name: 'Nick'}] console.log(unique);
The function we passed to the Array.filter method gets called with each element in the array.
On each iteration, we check if the unique IDs array contains the ID of the current element.
If it does contain it, then we have a duplicate.
If it doesn't contain it, we need to add the ID to the unique IDs array and return a truthy value from the function.
filter
method only adds an element to the results array if the function passed to the method returns a truthy value.The results array does not contain any duplicates.
id
property as the object's identifier. In your case the object's identifier might be called something else.In essence, our solution is to only add unique IDs into the uniqueIds
array
and only add the object into the results array if the object's ID is not in the
uniqueIds
array.
We can also use a Set object to remove all duplicates from an array of objects.
const arr = [ {id: 1, name: 'Tom'}, {id: 1, name: 'Tom'}, {id: 2, name: 'Nick'}, {id: 2, name: 'Nick'}, ]; const uniqueIds = new Set(); const unique = arr.filter(element => { const isDuplicate = uniqueIds.has(element.id); uniqueIds.add(element.id); if (!isDuplicate) { return true; } return false; }); // 👇️ [{id: 1, name: 'Tom'}, {id: 2, name: 'Nick'}] console.log(unique);
The Set
object only stores unique values, so even if we add the same value to
a Set
multiple times, it would only be contained once in the Set
.
We use the same approach, however we don't have to check before adding each ID
to the Set
because duplicate IDs get automatically removed anyway.
Instead of using the includes
method we can use the has
method on the
Set
object and instead of pushing the ID into the uniqueIds
array, we use
the add
method on the Set
.