To check if a Set contains an array in JavaScript, you can use the has() method. This method returns a Boolean, indicating whether the given value is in the Set or not.
In order to check if a Set contains an array, you can pass the array as a reference to the has() method. If the set has the array, it will return true, else false.
Check If A Set Contains An Array In JavaScript
Below is an example of how to check if a Set contains an array in JavaScript.
var arr1 = [1,2,3];
let mySet = new Set([arr1, [4,5,6]]);
console.log(mySet.has(arr1)); // true
console.log(mySet.has([4,5,6])); // false
As you can see from the example above, the has() method can differentiate between two arrays that have the same values but are stored as different references. This is because the has() method checks for reference equality, not value equality.
This is why [4,5,6] when checked against mySet returns false, even though it has the same values as the array in the set.
If you do not have the reference to the array but want to check if a Set contains an array with specific values, you can use a for loop and do a String check of the values.
var arr1 = [‘a’,’b’,’c’];
let mySet = new Set([arr1, [‘d’, ‘e’, ‘f’]]);
for(let val of mySet){
if(val.toString() === arr1.toString()){
console.log("set has array");
break;
}
} // set has array
As you can see from the example above, we first convert the values in the Set to strings using the toString() method. We then compare these strings with the string representation of our array. If they are equal, it means that the Set contains an array with the same values.
Conclusion
To sum up, there are two ways to check if a Set contains an array in JavaScript. You can either use the has() method to check for reference equality or you can use a for loop and do a String check of the values.
The has() method is way faster than the for loop method, but it only works if you have the reference to the array. If you do not have the reference, then the for loop method is your best bet.