# JS: 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 }```
Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put \$5 at patreon.

If you have a question, put \$5 at patreon and message me.