8

Does Javascript supports Sets(list with unique objects only) ?

I have found this link, but from what I remember foreach in JS in not supported by every browser.

IAdapter
  • 62,595
  • 73
  • 179
  • 242

5 Answers5

6

Are your keys strings?

Every JavaScript object is a map, which means that it can represent a set.

As illustrated in the page you mentioned, each object will accept only one copy of each key (attribute name). The value for the key/attribute doesn't matter.

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
4

jshashtable would allow you to store any object as a key, and use the same pattern as in the link you gave. In addition it supplies a method to get an array of keys, which you can then iterate over. It also has good cross-browser support, so should fit nicely into any environment.

MattJ
  • 7,924
  • 1
  • 28
  • 33
  • thx for the link, i have also found that, but if I can use a map for that than using external lib is not needed. – IAdapter Dec 27 '10 at 15:06
  • A map won't work out of the box for non-string objects, which is the point of jshashtable. – MattJ Dec 27 '10 at 15:22
  • In case it's not clear, there is a `HashSet` wrapper available to download with jshashtable: http://code.google.com/p/jshashtable/downloads/detail?name=jshashset.js&can=2&q=#makechanges – Tim Down Dec 27 '10 at 18:15
2

Now with ES6 (and polyfills/shims like corejs) you have them:

Set - JavaScript | MDN

Example:

var mySet = new Set([1, 2, 3, 2, 1]);  // => [1, 2, 3]
console.log(mySet.size);
console.log(mySet.has(3));
mySet.forEach(function(x){console.log(x)});

The Polifill is required since it is not supported by older browsers, so you can ignore it if you are aiming only at the latest ones.

Frank Orellana
  • 1,820
  • 1
  • 22
  • 29
0

You probably remember the Array.forEach() that is indeed not supported by older Opera and all IE browsers - the for (var x in ...) is part of the "native" JS as far as I know and is supported by all browsers.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
0

JavaScript do support Set. Here is the link to canIuse website. It is supported by Chrome, Edge, Safari, Firefox, Opera and even IE. To declare set you can use Set() constructor.

let set = new Set();
set.add("John);

In this way you can use sets.