JS: Set Union, Intersection, Difference 🚀

By Xah Lee. Date: . Last updated: .

Union of Sets

// 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 of Sets

// 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 }

JavaScript, Set Object