Remove Duplicates from an Array of Objects in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 13 20212 min read

Remove Duplicates from an Array of Objects #

To remove all duplicate objects from an array:

  1. Create an empty array that will store the unique object IDs.
  2. Call the filter() method, passing it a function.
  3. On each iteration check if the unique IDs array contains the ID of the current element.
  4. If the ID is not contained, add the object's ID to the unique IDs array and the object to the results array.
index.js
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; } }); // ๐Ÿ‘‡๏ธ [{id: 1, name: 'Tom'}, {id: 2, name: 'Nick'}] console.log(unique);

The function we pass to the Array.filter method gets called with each element in the array.

On each iteration we check if the unique ID's 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.

The 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.

Note that in this particular scenario we're using the 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.

index.js
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; } }); // ๐Ÿ‘‡๏ธ [{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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee