Sometimes, we want to remove duplicate objects from an array using JavaScript.
In this article, we’ll look at how to remove duplicate objects from an array using JavaScript.
How to remove duplicate objects from an array using JavaScript?
To remove duplicate objects from an array using JavaScript, we can use some array methods.
For instance, we write:
const a = [{
"id": 10620,
"name": "Things to Print"
},
{
"id": 10620,
"name": "Things to Print"
},
{
"id": 4334,
"name": "Interesting"
}
]
const newA = [...new Set(a.map(JSON.stringify))].map(JSON.parse)
console.log(newA)
to remove duplicate objects from a
by mapping a
‘s entries to strings by calling map
with JSON.stringify
.
Then we create a new set from the returned array with Set
.
Next, we spread that back to an array.
And then we call map
on the new array with JSON.parse
to convert it back to an object.
Therefore, newA
is
[{
id: 10620,
name: "Things to Print"
}, {
id: 4334,
name: "Interesting"
}]
Conclusion
To remove duplicate objects from an array using JavaScript, we can use some array methods.