JavaScript: Set Union, Intersection, Difference

By Xah Lee. Date: . Last updated: .

ES2015 does not provide functions to do set union, intersection, difference. Here are the code to do so.

Union

// return a union of all sets. Does not modify args. version 2016-11-18
const xah_set_union = (...sets) => {
    let X = new Set();
    sets.forEach( S => S.forEach( e => X.add(e)))
    return X;
 };

// test
let s1 = new Set([3,4,5]);
let s2 = new Set([5,6]);
let s3 = new Set([11,12]);
console.log(xah_set_union(s1, s2, s3)); // Set { 3, 4, 5, 6, 11, 12 }

Intersection

// return the intersection of all sets. Does not modify args. version 2016-11-18
const xah_set_intersection = (...sets) => sets.reduce(
 ( A, B) => {
     let X = new Set();
     B.forEach( (v => { if ( A.has(v) ) X.add(v) })) ;
     return X;
 } );

// test
let s1 = new Set([3,6,4,5]);
let s2 = new Set([6,3]);
let s3 = new Set([11,6, 12, 3]);
console.log(xah_set_intersection(s1, s2, s3)); // Set { 6, 3 }

Difference of Sets

// return the difference of all sets. That is, A - B - C - D .... Does not modify args. version 2016-11-18
const xah_set_difference = ((...sets) => sets.reduce(
    ((A, B) => {
        let X = new Set(A);
        B.forEach( v => {if ( X.has(v) ) X.delete(v)});
        return X;
    })
));

// test
let s1 = new Set([3,4,5,6]);
let s2 = new Set([5,3]);
let s3 = new Set([4]);
console.log(xah_set_difference(s1, s2, s3)); // Set { 6 }

Set Topic

  1. JavaScript: the Set Object Tutorial
  2. JavaScript: Set Union, Intersection, Difference
  3. JavaScript: Set Object
  4. JavaScript: Set.prototype
  5. JavaScript: Set.prototype.forEach
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.