Remove Duplicates from an Array of Objects in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Remove Duplicates from an Array of Objects #

To remove the duplicates from an array of objects:

  1. Create an empty array that will store the unique object IDs.
  2. Use the Array.filter() method to filter the array of objects.
  3. Only include objects with unique IDs in the new 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; } 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 (object) in the array.

On each iteration, we check if the unique IDs array contains the ID of the current element.

If the ID is contained in the unique IDs array, we have a duplicate.

If the ID isn't contained in the unique IDs array, we add the ID and return true 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.

We use the id property as the object's identifier in the example. 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; } 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, the value is only 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.

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.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.