Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set data structure of Java in javascript/jQuery

Tags:

Is there any way to create Set data structure(Unique Collections) like java in javascript?

like image 910
Suvonkar Avatar asked Jun 15 '10 06:06

Suvonkar


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

What is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").


2 Answers

For a set of strings, I would just use a object with the value true.

var obj = {}; obj["foo"] = true; obj["bar"] = true;  if(obj["foo"]) {   // foo in set } 

This is basically how HashSet works in Java, assuming the JavaScript object is implemented as a hashtable (which is typical).

like image 87
Matthew Flaschen Avatar answered Sep 22 '22 01:09

Matthew Flaschen


I have written a JavaScript implementation of a hash set that is similar to Java's HashSet. It allows any object (not just strings) to be used as a set member. It's based on the keys of a hash table.

http://code.google.com/p/jshashtable/downloads/list

Documentation will follow shortly, I promise. For now, the source should give you the API pretty clearly, and here's an example:

var s = new HashSet(); var o1 = {name: "One"}, o2 = {name: "Two"}; s.add(o1); s.add(o2); s.add(o2); s.values(); // Array containing o1 and a single reference to o2 
like image 28
Tim Down Avatar answered Sep 19 '22 01:09

Tim Down