Skip to content

How to Remove Duplicate Object from Array JavaScript

Last updated on March 12, 2020

In this blog post, you’ll learn the trick about using array and how to remove duplicate Object from array in JavaScript.

We might end up in this situation lots of time but I would like to have this written to save time from small stuff.

const users = [ { id: "1", name: "Jack" }, { id: "2", name: "John" }, { id: "3", name: "Ravaan" }, { id: "4", name: "Rameen" } ];

Let’s consider the above users array of objects.

To arrive for the solution, first we would think about using filter operator of an Array.

Filter operator which accepts callback function to check the existence of an id property.

Remove duplicate Object from Array with Filter

let uniqueUsers = [];
users.filter(item => {
  if(item) {
    const exists = uniqueUsers.find(user => (user && user.id === item.id));
    // Exists represents an Object.
    if(!exists) {
        uniqueUsers.push(item);
    }
  }
});

The above way is the well known one which everybody does.

But, One more way is also there.

With JSON.stringify( )

We take an advantage of ES6 feature called, Set which removes duplicate.

const uniqueUsers = [...new Set(users.map(user => JSON.stringify(user)))].map(s => JSON.parse(s))

As we know to solve this problem we will have multiple ways to derive the solution. But finally wins based on performance gain.

References

Published inAngularFrameworksJavaScriptReact