Disjointed Iterables in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will dive into the concept of disjointed iterables in JavaScript. We will learn how to use the Set constructor and Array.prototype.every() method to check if two iterables have any common values. By the end of this lab, you will have a solid understanding of how to implement this functionality in your JavaScript code.


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-28275{{"`Disjointed Iterables in JavaScript`"}} javascript/data_types -.-> lab-28275{{"`Disjointed Iterables in JavaScript`"}} javascript/arith_ops -.-> lab-28275{{"`Disjointed Iterables in JavaScript`"}} javascript/comp_ops -.-> lab-28275{{"`Disjointed Iterables in JavaScript`"}} javascript/spread_rest -.-> lab-28275{{"`Disjointed Iterables in JavaScript`"}} end

Checking for Disjointed Iterables

To check if two iterables have no common values, you can use the isDisjoint function.

Here's how to use it:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Create a new Set object from each iterable using the Set constructor.
  3. Use Array.prototype.every() and Set.prototype.has() to check that the two iterables have no common values.
const isDisjoint = (a, b) => {
  const sA = new Set(a),
    sB = new Set(b);
  return [...sA].every((v) => !sB.has(v));
};

Here are some examples:

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

Summary

Congratulations! You have completed the Disjointed Iterables lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like