What if a JavaScript Set holds objects as elements?
If you put objects as elements into a JavaScript Set, what is the criterion for deciding whether each element is unique? Does it compare even the property values inside the objects?
It only compares the memory address.
Let’s look at an example.
let a = {a: 1};
let b = {a: 1};
let set = new Set([a, b]);
What’s the result?

So don’t try to use a Set to select distinct objects.
If your object has a unique value, use a Map with that value as the key.
Example
let a = {key: 'a', value: 1};
let b = {key: 'b', value: 1};
let arr = [a, b];
const map = new Map();
arr.forEach(element => map.set(element.key, element));
const uniqueArr = [...map.values()]

20211203
Leave a comment