Find duplicate objects in an array in JavaScript and Angular

Find duplicate objects in an array in JavaScript and Angular

There are two main approaches to find duplicate objects in an array in JavaScript and Angular:

Using the Set data structure:

  1. Create a new Set object.

  2. Iterate through the original array and add each object to the Set. The Set will automatically discard duplicates.

  3. Convert the Set back to an array to get the unique objects.

Here's an example implementation:

const originalArray = [
  { id: 1, name: 'John Doe' },
  { id: 2, name: 'Jane Doe' },
  { id: 1, name: 'John Doe' }, // Duplicate object
  { id: 3, name: 'Peter Jones' },
];

const uniqueObjects = new Set(originalArray);
const uniqueArray = Array.from(uniqueObjects);

console.log(uniqueArray); // Output: [{ id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' }, { id: 3, name: 'Peter Jones' }]

Using the Array.reduce() method:

  1. Initialize an empty array to store the unique objects.

  2. Iterate through the original array. For each object, check if it exists in the unique objects array using the some() method. If it doesn't exist, add it to the unique objects array.

Here's an example implementation:

const originalArray = [
  { id: 1, name: 'John Doe' },
  { id: 2, name: 'Jane Doe' },
  { id: 1, name: 'John Doe' }, // Duplicate object
  { id: 3, name: 'Peter Jones' },
];

const uniqueObjects = originalArray.reduce((acc, item) => {
  if (!acc.some(obj => obj.id === item.id && obj.name === item.name)) {
    acc.push(item);
  }
  return acc;
}, []);

console.log(uniqueObjects); // Output: [{ id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' }, { id: 3, name: 'Peter Jones' }]

Both of these approaches are efficient and can be used to find duplicate objects in an array of any size. The Set approach is generally considered more concise and easier to understand, while the Array.reduce() approach may be more performant for very large arrays.


  • Date: