98

I want to convert JavaScript Set to string with space.

For example, if I have a set like:

var foo = new Set();
foo.add('hello');
foo.add('world');
foo.add('JavaScript');

And I'd like to print the string from the set: hello world JavaScript (space between each element).

I tried below codes but they are not working:

foo.toString(); // Not working
String(foo); // Not working

Is there simplest and easiest way to convert from Set to string?

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
KimchiMan
  • 4,836
  • 6
  • 35
  • 41

2 Answers2

185

You can use Array.from:

Array.from(foo).join(' ')

or the spread syntax:

[...foo].join(' ')
isanae
  • 3,253
  • 1
  • 22
  • 47
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

You can iterate through the set and build an array of the elements and return the desired string by joining the array.

var foo = new Set();
foo.add('hello');
foo.add('world');
foo.add('JavaScript');
let strArray = [];

for(str of foo){
  strArray.push(str);
}

console.log(strArray.join(" "));
Ketan Ramteke
  • 10,183
  • 2
  • 21
  • 41