Borislav Hadzhiev
Sun Nov 07 2021·2 min read
Photo by Alex Bertha
Use the has()
method to check if a Set
contains an object, e.g.
set.has(obj)
. The object has to be passed by reference to the has
method to
get a reliable result. The has
method tests for the presence of a value in a
Set
and returns true
if the value is contained in the Set
.
const obj = {id: 1}; const set1 = new Set([obj, {id: 2}]); console.log(set1.has(obj)); // 👉️ true
We passed an object by reference to the
Set.has
method to check if the object is contained in the Set
.
Note that the object has to be passed by reference to the has
method. Passing
the object by value would not work.
const obj = {id: 1}; const set1 = new Set([obj, {id: 2}]); console.log(set1.has({id: 1})); // 👉️ false
If you don't have a reference to the object you're checking for, you can use a for...of loop to iterate over the Set and check for the presence of the specific object.
const set1 = new Set([{id: 1}, {id: 2}]); let containsObject = false; for (const obj of set1) { if (obj.id === 1) { containsObject = true; break; } } console.log(containsObject); // 👉️ true
We initialized a containsObject
variable and set it to false
. The for...of
loop allows us to iterate over the Set
and check if the specific object is
contained in it.
If we find the object, we use the break
keyword to exit the loop and avoid
unnecessary work.
has
method is much more performant, especially if the object is towards the end of the Set
, or is not contained in the Set
at all.