Subset of iterable

Isabelle Viktoria Maciohsek · JavaScript, Array · Oct 22, 2020

Checks if the first iterable is a subset of the second one, excluding duplicate values.

const subSet = (a, b) => {
  const sA = new Set(a), sB = new Set(b);
  return [...sA].every(v => sB.has(v));
};
subSet(new Set([1, 2]), new Set([1, 2, 3, 4])); // true
subSet(new Set([1, 5]), new Set([1, 2, 3, 4])); // false

Recommended snippets

  • Superset of iterable

    JavaScript, Array

    Checks if the first iterable is a superset of the second one, excluding duplicate values.

  • Checks if the elements of the first array are contained in the second one regardless of order.

  • Disjointed iterables

    JavaScript, Array

    Checks if the two iterables are disjointed (have no common values).