I'm looking for a decent implementation of a set data structure in JavaScript. It should be able to support elements that are plain JavaScript objects.
So far I only found Closure Library's structs.Set, but I don't like the fact that it modifies my data.
Learn about how to use and when to use Set in JavaScript. The Set object allows you to create a collection of unique values (each value can occur only once). Set can contain any type of value (primitives or object reference).
Set receives iterable object as its input parameter, and will create set object respectively. Hence, we can construct a set from an array — but it will only include distinct elements from that array, aka no duplicate. And of course, we can also convert a set back to array using Array. from() method.
A set is a data structure that stores unique elements of the same type in a sorted order. Each value is a key, which means that we access each value using the value itself. With arrays, on the other hand, we access each value by its position in the container (the index). Accordingly, each value in a set must be unique.
ECMAScript 6 has it
Spec: http://www.ecma-international.org/ecma-262/6.0/#sec-set-constructor
Usage: https://github.com/lukehoban/es6features#map--set--weakmap--weakset
Example:
var s = new Set() s.add("hello").add("goodbye").add("hello") s.size === 2 s.has("hello") === true
A module that implements it for browsers without support: https://github.com/medikoo/es6-set
You could build a simple wrapper around the keys of a hash table provided by my jshashtable. I have one knocking around somewhere that I will dig out later.
UPDATE
I have completed and tested an implementation of HashSet and uploaded it to the jshashtable project on GitHub. You can download it or view the source.
var s = new HashSet(); var o1 = {name: "One"}, o2 = {name: "Two"}; s.add(o1); s.add(o2); s.values(); // Array containing o1 and o2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With