less than 1 minute read

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?

result1

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()]

result2

20211203

Leave a comment