How to Remove All Duplicates from an Array of Objects
When working with JavaScript, you may come across a situation where you need to remove all duplicates from an array of objects. This can be a common problem when dealing with data manipulation or filtering. In this blog post, we will explore multiple solutions to tackle this issue.
Solution 1: Using Set and Array.from()
One way to remove duplicates from an array of objects is by utilizing the Set
data structure and the Array.from()
method. The Set
object allows you to store unique values of any type, including objects.
Here’s an example:
const array = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John' },
{ id: 3, name: 'Mike' },
{ id: 2, name: 'Jane' }
];
const uniqueArray = Array.from(new Set(array.map(JSON.stringify))).map(JSON.parse);
console.log(uniqueArray);
The above code creates a new Set
by mapping each object to its stringified version using JSON.stringify()
. This ensures that the objects are compared based on their string representation. Then, Array.from()
is used to convert the Set
back to an array. Finally, JSON.parse()
is applied to each element to convert them back to objects.
The output of the above code will be:
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Mike' }
]
Solution 2: Using a Helper Function
If you prefer a more concise approach, you can create a helper function that takes an array of objects and removes duplicates based on a specific property.
Here’s an example:
function removeDuplicates(array, property) {
return array.filter((obj, index, self) =>
index === self.findIndex((o) => o[property] === obj[property])
);
}
const array = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John' },
{ id: 3, name: 'Mike' },
{ id: 2, name: 'Jane' }
];
const uniqueArray = removeDuplicates(array, 'id');
console.log(uniqueArray);
In the above code, the removeDuplicates()
function uses the filter()
method to iterate over the array and keep only the objects that have a unique value for the specified property. The findIndex()
method is used to find the index of the first occurrence of an object with the same property value.
The output of the above code will be the same as in Solution 1.
Now that you have learned two different approaches to remove duplicates from an array of objects, you can choose the one that best suits your needs. Happy coding!
Leave a Reply