DEV Community

loading...

Discussion on: Remove Duplicates With Set() - Full-Stop

Collapse
bytebodger profile image
Adam Nathaniel Davis Author • Edited

I did edit the original article slightly to indicate that it works with scalar (primitive) values. But I hadn't really thought of this as much of a "gotcha", because two objects that look the same... are not the same.

FWIW, this approach actually works with arrays and objects, if they are truly the same array/object. In other words, you can do something like this:

const anObject = {one: 'uno', two: 'dos'};
const anotherObject = anObject;
const anArray = [anObject, anotherObject];
const noDupes = [...new Set(anArray)];
Enter fullscreen mode Exit fullscreen mode

And the resulting noDupes array will only contain one object. But if you do this:

const anObject = {one: 'uno', two: 'dos'};
const anotherObject = {one: 'uno', two: 'dos'};
const anArray = [anObject, anotherObject];
const noDupes = [...new Set(anArray)];
Enter fullscreen mode Exit fullscreen mode

noDupes will contain two objects. Because, even though anObject and anotherObject look the same to our eye, they are not the same value.