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:
Create a new
Setobject.Iterate through the original array and add each object to the
Set. TheSetwill automatically discard duplicates.Convert the
Setback 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:
Initialize an empty array to store the unique objects.
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:
