Subset of Iterable

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28631{{"`Subset of Iterable`"}} javascript/data_types -.-> lab-28631{{"`Subset of Iterable`"}} javascript/arith_ops -.-> lab-28631{{"`Subset of Iterable`"}} javascript/comp_ops -.-> lab-28631{{"`Subset of Iterable`"}} javascript/spread_rest -.-> lab-28631{{"`Subset of Iterable`"}} end

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 Set object from each iterable using the Set constructor.
  • Use Array.prototype.every() and Set.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.

Other JavaScript Tutorials you may like