Introduction
We can remove duplicates from an array of objects using the following methods,
Using Set and Array.from() method
This method involves converting the array of objects into a Set object, automatically removing duplicates, and then converting it back into an array using Array.from().
let arr = [{
id: 1,
name: 'John'
}, {
id: 2,
name: 'Jane'
}, {
id: 1,
name: 'John'
}];
let uniqueArray = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
Using filter() method
This method uses the filter() method to iterate over the array of objects and check if the current object already exists in a new array. If it doesn't, it is added to the new array.
let arr = [{
id: 1,
name: 'John'
}, {
id: 2,
name: 'Jane'
}, {
id: 1,
name: 'John'
}];
let uniqueArray = arr.filter((obj, index, self) => index === self.findIndex((t) => (t.id === obj.id && t.name === obj.name)));
Using reduce() method
This method uses the reduce() method to iterate over the array of objects and check if the current object already exists in a new array. If it doesn't, it is added to the new array.
let arr = [{
id: 1,
name: "John"
}, {
id: 2,
name: "Jane"
}, {
id: 3,
name: "John"
}, {
id: 4,
name: "Jane"
}];
let uniqueArr = arr.reduce((acc, current) => {
let exists = acc.some(item => item.id === current.id && item.name === current.name);
if (!exists) {
acc.push(current);
}
return acc;
}, []);
console.log(uniqueArr);
These are the many ways to remove duplicates from an array of objects.