Check if a Set contains an Array in JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

Check if a Set contains an Array #

Use the has() method to check if a Set contains an array, e.g. set.has(arr). The array 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 arr = ['one']; const set1 = new Set([arr, ['two']]); console.log(set1.has(arr)); // ๐Ÿ‘‰๏ธ true

We passed an array by reference to the Set.has method to check if the array is contained in the Set.

Note that the array has to be passed by reference to the has method. Passing the array by value would not work.

index.js
const arr = ['one']; const set1 = new Set([arr, ['two']]); console.log(set1.has(['one'])); // ๐Ÿ‘‰๏ธ false
This is because the array 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 array you're checking for, you can use a for...of loop to iterate over the Set and check for the presence of the specific array.

index.js
const set1 = new Set([['one', 'two'], ['three']]); let containsArray = false; const checkForArr = ['one', 'two']; for (const arr of set1) { if (arr.toString() === checkForArr.toString()) { containsArray = true; break; } } console.log(containsArray); // ๐Ÿ‘‰๏ธ true

We initialized a containsArray variable and set it to false. The for...of loop allows us to iterate over the Set and check if the specific array is contained in it.

We used the Array.toString method to get a string containing the elements of the array. This would only evaluate to true if both of the arrays have the same elements in the same order.

index.js
console.log(['one', 'two'].toString()); // ๐Ÿ‘‰๏ธ "one,two" // ๐Ÿ‘‡๏ธ true console.log( ['one', 'two'].toString() === ['one', 'two'].toString() ); // ๐Ÿ‘‡๏ธ false console.log( ['one', 'two'].toString() === ['two', 'one'].toString() );

If we find the array, 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 array, using the has method is much more performant, especially if the array 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