Introduction
In this lab, we will explore how to check if a subset of values in one iterable is contained in another iterable. We will use the Set constructor and Array.prototype.every() to create a function that checks if all values in the first iterable are present in the second iterable. By the end of this lab, you will have a better understanding of how to work with sets in JavaScript.
Checking if a Subset of an Iterable is Contained in Another Iterable
To practice coding, open the Terminal/SSH and type node. This function checks whether the first iterable is a subset of the second iterable, excluding duplicate values.
To achieve this, you can do the following:
- Create a new
Setobject from each iterable using theSetconstructor. - Use
Array.prototype.every()andSet.prototype.has()to check if every value in the first iterable is contained in the second iterable.
Here's an example implementation:
const subSet = (a, b) => {
const setA = new Set(a);
const setB = new Set(b);
return [...setA].every((value) => setB.has(value));
};
You can use the subSet function by passing in two sets to compare. For example:
subSet(new Set([1, 2]), new Set([1, 2, 3, 4])); // true
subSet(new Set([1, 5]), new Set([1, 2, 3, 4])); // false
Summary
Congratulations! You have completed the Subset of Iterable lab. You can practice more labs in LabEx to improve your skills.