To remove the duplicates from an array of objects:
- Create an empty array that will store the unique object IDs.
- Use the Array.filter() method to filter the array of objects.
- Only include objects with unique IDs in the new array.
// ✅ If you need to check for uniqueness based on a single property
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);
// ------------------------------------------------------------
// ------------------------------------------------------------
// ------------------------------------------------------------
// ✅ If you need to check for uniqueness based on multiple properties
const arr2 = [
{id: 1, name: 'Tom'},
{id: 1, name: 'Tom'},
{id: 1, name: 'Alice'},
{id: 2, name: 'Nick'},
{id: 2, name: 'Nick'},
{id: 2, name: 'Bob'},
];
const unique2 = arr2.filter((obj, index) => {
return index === arr2.findIndex(o => obj.id === o.id && obj.name === o.name);
});
// [
// { id: 1, name: 'Tom' },
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Nick' },
// { id: 2, name: 'Bob' }
// ]
console.log(unique2);