Does Javascript supports Sets?
Asked Answered
A

5

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.

Areaway answered 27/12, 2010 at 14:41 Comment(0)
S
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.

Spiculate answered 27/12, 2010 at 14:47 Comment(2)
The article you link is the same page 01 linked to.Shackleton
thx for clarification, ive just found that article very hard to read, so I tried to guess what he meant :PAreaway
H
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.

Hyperaesthesia answered 27/12, 2010 at 14:49 Comment(3)
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.Areaway
A map won't work out of the box for non-string objects, which is the point of jshashtable.Hyperaesthesia
In case it's not clear, there is a HashSet wrapper available to download with jshashtable: code.google.com/p/jshashtable/downloads/…Municipality
P
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.

Plethora answered 18/10, 2016 at 4:38 Comment(0)
C
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.

Clarenceclarenceux answered 27/12, 2010 at 14:58 Comment(0)
E
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.

Enschede answered 17/7, 2022 at 8:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.