DEV Community

Discussion on: Removing duplicates in an Array of Objects in JS with Sets

Collapse
 
imcorfitz profile image
Corfitz • Edited

There is a difference between Tony's and Matt's approach in how the final array will look like.

Matt's approach is adding the id for each entry it loops through to a Set and checks whether or not it has been ´seen´ before or not, and return the object if 'no' is the case. So if we look at the returned object with ID: 2, Matt will return the object with name: "test2" as it will consider the next object a duplicate and skip it.

Tony's approach is by creating a new map using ID as a key - which has to be unique - and then extracts the values. E.g. [1: { id: 1, name: "test1" }, 2: { id: 2, name: "test2" }....] etc. What this means though, is that even though id: 2 has been added to the map, it is simply overwritten by the third item in the array, thus Tony will return name: "test3" for ID: 2.

Just keep this in mind whether you want the first object or the last object by a duplicated identifier to be the truth.