views:

104

answers:

3

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

A: 

I could say no... javascripts' data structures are Objects and Arrays...

well, with Objects or Arrays, you could make something similar to Set of java..

and here is a very good one you could use...

Reigel
+3  A: 

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

var o = {};
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).

Matthew Flaschen
+1  A: 

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
Tim Down