Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript have an implementation of a set data structure?

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.

like image 789
Tim Molendijk Avatar asked Mar 26 '10 13:03

Tim Molendijk


People also ask

Is there a Set data structure in JavaScript?

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

Is Set an array in JavaScript?

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.

What is a Set data structure?

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.


2 Answers

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 
like image 38
Tim Down Avatar answered Sep 27 '22 21:09

Tim Down