Check if a Set contains an Object in JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

banner

Photo by Alex Bertha

Check if a Set contains an Object #

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.

index.js
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.

index.js
const obj = {id: 1}; const set1 = new Set([obj, {id: 2}]); console.log(set1.has({id: 1})); // ๐Ÿ‘‰๏ธ false
This is because the object we're checking for is at a different location in memory and has a completely different reference.

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.

index.js
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.

It there's a way for you to get a reference to the object, using the 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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee