2

I'm looking for Set and Set operations in Javascript for intersection, union and difference instead of having to write them manually. Here's equivalent Java code:

    Set<Integer> toMerged = new HashSet<Integer>(to);
    toMerged.addAll(memory);

    Set<Integer> toFiltered = new HashSet<Integer>(toMerged);
    Set<Integer> memoryFiltered = new HashSet<Integer>(toMerged);

    toFiltered.retainAll(lookupSet);
    memoryFiltered.removeAll(lookupSet);

As seen in code above, I'm looking for for equivalent addAll, retainAll and removeAll methods in a Set implementation in Javascript. Thanks for any insights.

user203617
  • 523
  • 8
  • 20
  • 1
    Possible duplicate of of http://stackoverflow.com/questions/2342749/is-there-a-library-for-a-set-data-type-in-javascript – jcubic Jun 06 '14 at 12:42

1 Answers1

0

Unfortunately, the specified intersection, union, and difference operations are unavailable in the current Javascript Set implementation.
However, on the MDN page for the Set class, you can find possible implementations.

function union(setA, setB) {
  const _union = new Set(setA);
  for (const elem of setB) {
    _union.add(elem);
  }
  return _union;
}
function intersection(setA, setB) {
  const _intersection = new Set();
  for (const elem of setB) {
    if (setA.has(elem)) {
      _intersection.add(elem);
    }
  }
  return _intersection;
}
function difference(setA, setB) {
  const _difference = new Set(setA);
  for (const elem of setB) {
    _difference.delete(elem);
  }
  return _difference;
}