9

How to convert Set to Array? gives three answers for converting a Set to an Array, none of which currently work in the Chrome browser.

Let's say I have a simple Set

var set_var = new Set(['a', 'b', 'c']);

I can iterate through my variable and add the elements to an empty array

var array_var = [];
set_var.forEach(function(element){array_var.push(element)});

But are there any other ways to do this that have wider browser support?

Community
  • 1
  • 1
Cecilia
  • 4,103
  • 2
  • 27
  • 68
  • 2
    `Set` itself is part of ES6 Harmony. You won't find "wider browser support," given this is experimental technology for the time being. There are ways to iterate without `Array.prototype.forEach`, but those ways would be for browsers that don't support `Set` to begin with. – Sampson Apr 14 '15 at 22:30
  • @JonathanSampson Okay, I hear you. Let's focus on Chrome then. Chrome does support `Set` just not all the functionality that other browsers support. Are there other ways to convert the Set to an Array in Chrome? – Cecilia Apr 14 '15 at 22:50
  • What about this, its more complicated but if you only want another way: var mySet = Set(['a','b','c']); iter = mySet.keys(); for(var i = 0; i < mySet.size; i++){ console.log(iter.next().value[0]) } – Kelvin17 Apr 17 '15 at 22:55
  • 2
    Possible duplicate of [How to convert Set to Array?](http://stackoverflow.com/questions/20069828/how-to-convert-set-to-array) – Eric Oct 27 '15 at 21:49

1 Answers1

1

Why not give a try with set iterator?

function setToArray(set) {
  var it = set.values(),
      ar = [],
      ele = it.next();

  while(!ele.done) {
    ar.push(ele.value);
    ele = it.next();
  }

  return ar;
}

setToArray(new Set(['a', 'b', false, 0, 'c'])); // ["a", "b", false, 0, "c"]
Leo
  • 11,955
  • 4
  • 37
  • 58
  • Are there any advantages with a set iterator? – Cecilia May 01 '15 at 22:06
  • @Cecilia I'm not sure what you are looking for, performance, compatibility, or anything else. It's just one of many approaches. Honestly, I don't see significant difference from yours. – Leo May 02 '15 at 02:10
  • This implementation will fail if Set contains Falsy value. Always check current.finished instead of current.value – garkin Dec 09 '15 at 07:43
  • @garkin Missed that point given PO's sample data, updated answer. Thank you. – Leo Dec 09 '15 at 13:38