Categories
JavaScript Answers

How to remove duplicate objects from JSON array with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *