Sometimes, we want to remove duplicate objects from JSON array with JavaScript.
In this article, we’ll look at how to remove duplicate objects from JSON array with JavaScript.
How to remove duplicate objects from JSON array with JavaScript?
To remove duplicate objects from JSON array with JavaScript, we can use a set.
For instance, we write
const data = [
{ Grade: "Math K", Domain: "Counting & Cardinality" },
{ Grade: "Math K", Domain: "Geometry" },
{ Grade: "Math 1", Domain: "Counting & Cardinality" },
{ Grade: "Math 1", Domain: "Orders of Operation" },
{ Grade: "Math 2", Domain: "Geometry" },
];
const set = new Set(data.map((item) => JSON.stringify(item)));
const dedup = [...set].map((item) => JSON.parse(item));
to call data.map
to map each object in data
to JSON strings with JSON.stringify
.
Then we put them all in a set with the Set
constructor.
Next, we spread the set
back to an array then call map
to map them back to objects with JSON.parse
.
Conclusion
To remove duplicate objects from JSON array with JavaScript, we can use a set.