remove duplicate object from array javascript

Remove Duplicate Object from Array in JavaScript

As a programmer, I often come across the situation where I need to remove duplicate objects from an array using JavaScript. Let me share with you the solution I found that worked for me.

Using Set

The easiest and most efficient way to remove duplicate objects from an array is to use a Set object in JavaScript. Here is the code to do so:


const arr = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 1, name: 'John'}, {id: 3, name: 'James'}];

const uniqueArr = [...new Set(arr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));

console.log(uniqueArr);

In the above code, we are creating a Set object from the array of objects and then converting it back to an array using the spread operator. We are using JSON.stringify and JSON.parse methods to compare the objects by their string representation.

Using Filter and IndexOf

Another way to remove duplicate objects from an array is to use the filter method and indexOf method. Here is the code:


const arr = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 1, name: 'John'}, {id: 3, name: 'James'}];

const uniqueArr = arr.filter((item, index) => {
  return index === arr.findIndex(obj => JSON.stringify(obj) === JSON.stringify(item));
});

console.log(uniqueArr);

In the above code, we are using the filter method to filter out the objects from the array that do not meet the condition of having a unique string representation. We are using the findIndex method to get the index of the first occurrence of the object with the same string representation and then comparing it with the current index using the indexOf method.

Using Reduce and Some

One more way to remove duplicate objects from an array is to use the reduce method and some method. Here is the code:


const arr = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 1, name: 'John'}, {id: 3, name: 'James'}];

const uniqueArr = arr.reduce((acc, item) => {
  if (!acc.some(obj => JSON.stringify(obj) === JSON.stringify(item))) {
    acc.push(item);
  }
  return acc;
}, []);

console.log(uniqueArr);

In the above code, we are using the reduce method to iterate over the array of objects and accumulate unique objects in a new array. We are using the some method to check if the object with the same string representation already exists in the accumulator array.

These are three ways to remove duplicate objects from an array using JavaScript. You can choose the one that suits your needs and coding style.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe