Iterate over set elements

JavascriptEcmascript 6

Javascript Problem Overview


I have turned on the Chrome flag for experimental ECMAscript 6 features, one of which is Set. As I understand, the details of Set are broadly agreed upon by the spec writers.

I create a set a and add the string 'Hello'

a = Set();
a.add('Hello');

but how do I iterate over the elements of a?

for(let i of a) { console.log(i); }

gives "SyntaxError: Illegal let declaration outside extended mode"

for(var i of a) { console.log(i); }

gives "SyntaxError: Unexpected identifier"

for(var i in a) { console.log(i); }

gives Undefined

Is it possible to iterate over of a set in Chrome 26?

Javascript Solutions


Solution 1 - Javascript

A very easy way is to turn the Set into an Array first:

let a = new Set();
a.add('Hello');
a = Array.from(a);

...and then just use a simple for loop.

Be aware that Array.from is not supported in IE11.

Solution 2 - Javascript

Upon the spec from MDN, Set has a values method: > The values() method returns a new Iterator object that contains the values for each element in the Set object in insertion order.

So, for iterate through the values, I would do:

var s = new Set(['a1', 'a2'])
for (var it = s.values(), val= null; val=it.next().value; ) {
    console.log(val);
}

Solution 3 - Javascript

I use the forEach(..); function. (documentation)

Solution 4 - Javascript

There are two methods you can use. for...of and forEach

let a = new Set();
a.add('Hello');

for(let key of a) console.log(key)

a.forEach(key => console.log(key))

Solution 5 - Javascript

The of operator doesn't appear to be currently supported in Chrome. It seems that only FireFox versions 13 through 18 support it. It also appears that none of the browsers actually support Set although the page does say that some of the tests represent existence and not full functionality or coherence. So it might be that Set is partially implemented in Chrome.

Solution 6 - Javascript

You can also use the spread operator to convert a Set into an array (an alternative to Array.from(yourSet)).

const mySet = new Set();

mySet.add('a');
mySet.add('b')

const iterableSet = [...mySet];
// end up with: ['a', 'b']

// use any Array method on `iterableSet`
const lettersPlusSomething = iterableSet.map(letter => letter + ' something');

Solution 7 - Javascript

Even if the syntactic sugar for iteration hasn't been implemented yet, you can probably still use iterators.

http://www.2ality.com/2012/06/for-of-ff13.html explains

> The special method __iterator__ returns an iterator object. Such an object has a method next() that either returns the next element in the current iteration sequence or throws StopIteration if there are no more elements.

So you should be able to iterate over the set using

for (var it = mySet.__iterator__();;) {
  var element;
  try {
    element = it.next();
  } catch (ex) {
    if (ex instanceof StopIteration) {
      break;
    } else {
      throw ex;
    }
  }
  // Do something with element
}

You can also define a functional version of for…of like

function forOf(collection, f) {
  // jQuery.each calling convention for f.
  var applyToElement = f.bind(/* this */ collection, /* index */ void 0);
  for (var it = collection.__iterator__();;) {
    var element;
    try {
      element = it.next();
    } catch (ex) {
      if (ex instanceof StopIteration) {
        break;
      } else {
        throw ex;
      }
    }

    // jQuery.each return convention.
    if (applyToElement(element) === false) { break; }
  }
}

Solution 8 - Javascript

A simple functional approach is to just use forEach

const mySet = new Set([1, 2, 3])
mySet.forEach(a => { console.log(a) })
// 1 2 3

Solution 9 - Javascript

this worked for me

mySet.forEach(async(item) =>{
   await doSomething(item)
 })

Solution 10 - Javascript

let set = new Set();
set.add(1);
set.add(2);

// This will be an array now, now you can loop normally.
console.log([...set]);

Solution 11 - Javascript

@bizi's answer is close but it did not work for me. This worked on Firefox:

var s= new Set([1,2]),
     it = s.values();
 for (var val= it.next().value; val=it.next().value;) {
     console.log("set: "+val);
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRandomblueView Question on Stackoverflow
Solution 1 - JavascriptandyrandyView Answer on Stackoverflow
Solution 2 - JavascriptbiziView Answer on Stackoverflow
Solution 3 - JavascriptFranXhView Answer on Stackoverflow
Solution 4 - JavascriptAvadhut ThoratView Answer on Stackoverflow
Solution 5 - JavascriptVivin PaliathView Answer on Stackoverflow
Solution 6 - JavascriptSean WattersView Answer on Stackoverflow
Solution 7 - JavascriptMike SamuelView Answer on Stackoverflow
Solution 8 - Javascriptjpthesolver2View Answer on Stackoverflow
Solution 9 - Javascriptnik.ssView Answer on Stackoverflow
Solution 10 - JavascriptVasanth View Answer on Stackoverflow
Solution 11 - JavascriptTechView Answer on Stackoverflow