Lewis Donovan
1 min readApr 16, 2020

--

There’s a few comments relating to using new Set() on an array of objects. This won’t work right out of the box, but if your objects have a consistent property order (if you’re pulling from an API this will usually be the case), you can do the following:

const myObjectArray = [{...},{...}]
const uniqueArr = [...new Set(myObjectArray.map(JSON.stringify))].map(JSON.parse);

This will use map to iterate through the array of objects and useJSON.stringify() to convert each object into a serialised string. This means any duplicates will have an identical string value, which you’re passing to the new Set() so any duplicates will be filtered out.

Then we use map again to iterate through each of the strings and use JSON.parse() to convert them back to objects. What you’re left with is an array of objects, with the duplicates removed.

--

--

Lewis Donovan
Lewis Donovan

Written by Lewis Donovan

CTO at SonX, former Sony Music UK. Fascinated by coding, science and music. https://lewisdonovan.dev

No responses yet