Superset 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 use the Set constructor and Array.prototype.every() method to determine if one iterable is a superset of another. The lab will walk you through the creation of a function that checks if the first iterable contains all the elements of the second iterable, excluding any duplicates. By the end of the 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-28636{{"Superset of Iterable"}} javascript/data_types -.-> lab-28636{{"Superset of Iterable"}} javascript/arith_ops -.-> lab-28636{{"Superset of Iterable"}} javascript/comp_ops -.-> lab-28636{{"Superset of Iterable"}} javascript/spread_rest -.-> lab-28636{{"Superset of Iterable"}} end

Function to Check if One Set is a Superset of Another Set

To check if one set is a superset of another set, use the superSet() function. First, open the Terminal/SSH and type node to start practicing coding. Then, use the following steps:

  • Create a new Set object from each iterable using the Set constructor.
  • Use Array.prototype.every() and Set.prototype.has() to check that each value in the second iterable is contained in the first one.
  • The function returns true if the first iterable is a superset of the second one, excluding duplicate values. Otherwise, it returns false.
const superSet = (a, b) => {
  const sA = new Set(a),
    sB = new Set(b);
  return [...sB].every((v) => sA.has(v));
};

Use superSet() with two sets as arguments to check if one set is a superset of another set.

superSet(new Set([1, 2, 3, 4]), new Set([1, 2])); // true
superSet(new Set([1, 2, 3, 4]), new Set([1, 5])); // false

Summary

Congratulations! You have completed the Superset of Iterable lab. You can practice more labs in LabEx to improve your skills.