Since Javascript doesn't have a built in set datatype has anyone come across a decent library for sets and set operations like union, intersection, etc?
6 Answers
Have a look at JS.Set.
The JS.Set class can be used to model collections of unique objects. A set makes sure that there are no duplicates among its members, and it allows you to use custom equality methods for comparison as well as JavaScript’s === operator.
It contains methods like union, intersection, merge, etc ...

- 8,009
- 3
- 26
- 25
If you just want to have access to simple union, intersection functions, you could also try Underscore.js's built-in Array functions. It also provides a lot of more useful utilities for data manipulation, so try it if you haven't.

- 113
- 3
- 7
Sets are now native in ES2015.
let a = new Set([1,2,3]);
let b = new Set([1,2,4]);
let intersect = new Set([...a].filter(i => b.has(i)));
let union = new Set([...a, ...b]);
This works with transpiling using babel or just natively in firefox.

- 35,972
- 25
- 125
- 179
-
doesn't work for objects like lib in the answer does – gabe Jun 30 '22 at 16:58
Check out setjs. The API provides basic operations and the library is immutable by design.
Disclaimer: I'm the author.

- 26,573
- 12
- 79
- 105
immutable-js expose a powerfull set data-structure.
A simple example for node.js, which you can see in work here.
im = require("immutable")
const mySet = im.Set([1, "a", {value: Symbol()}])
// the .add and .delete methods do not modify mySet, but return a new set instance instead.
const newSet = mySet
.add(42)
.delete(1)
console.info("Does mySet have 42?", mySet.has(42))
console.info("Does newSet have 42?", newSet.has(42))

- 801
- 1
- 14
- 27
like have been mention there is now Set on JS. Depending on your purposes you also may be interested on https://github.com/fsvieira/cset (I am its author), its a lazzy set lib, with common set operation, including cartesian product.

- 31
- 3