DEV Community


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

bytebodger profile image
Adam Nathaniel Davis Author • Edited

As Vesa demonstrated, this only works on scalar values. The reason is pretty simple:

console.log({a: 1} === {a: 1}); // false
Enter fullscreen mode Exit fullscreen mode

You could kinda sorta get around this using the old JSON.stringify() hack:

const set1 = new Set([{ a: 1 }, { a: 1 }]);
console.log(set1.size); // 2

const set2 = new Set([JSON.stringify({ a: 1 }), JSON.stringify({ a: 1 })]);
console.log(set2.size); // 1

const set3 = new Set([['a'], ['a']]);
console.log(set3.size); // 2

const set4 = new Set([JSON.stringify(['a']), JSON.stringify(['a'])]);
console.log(set4.size); // 1
Enter fullscreen mode Exit fullscreen mode

Although that only "works" if the keys/elements are in the same order. It would also fail in any scenario where JSON.stringify() would fail - e.g., if the objects/arrays contain functions.