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?

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

1 Comment

doesn't work for objects like lib in the answer does
3

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

Disclaimer: I'm the author.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.