20

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?

Jason Christa
  • 12,150
  • 14
  • 58
  • 85

6 Answers6

19

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 ...

Sagi
  • 8,009
  • 3
  • 26
  • 25
7

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.

4

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.

Kit Sunde
  • 35,972
  • 25
  • 125
  • 179
3

Check out setjs. The API provides basic operations and the library is immutable by design.

Disclaimer: I'm the author.

Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105
1

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))
atevm
  • 801
  • 1
  • 14
  • 27
0

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.

fsvieira
  • 31
  • 3