Categories
JavaScript Answers

How to remove all duplicates from an array of objects with JavaScript?

Spread the love

To remove all duplicates from an array of objects with JavaScript, we convert the objects to JSON strings and put them in a set.

For instance, we write

const things = [];
things.push({ place: "here", name: "stuff" });
things.push({ place: "there", name: "morestuff" });
things.push({ place: "there", name: "morestuff" });

const newThings = Array.from(new Set(myData.map(JSON.stringify))).map(
  JSON.parse
);

to call myData.map with JSON.stringify to return an array of JSON strings converted from the objects in the things array.

And then we convert the array to a set with Set to remove the duplicate strings.

Next we call Array.from to convert the set back to an array.

And then we call map with JSON.parse to convert the JSON strings back to objects.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.