Is there any way to create Set data structure(Unique Collections) like java 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).
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").
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).
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
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