There are many ways to convert Set to String with a space separator in javascript.
set is a datastructure introduced in latest javascript let’s declare set
var set = new Set();
set.add('first');
set.add('second');
set.add('three');
if we want to return string from a set, It is not straightforward.
normally we will use below approaches to print any object.
console.log(set); //:[object Set]
console.log(set.toString()); //[object Set]
This is not what we are expecting instead we are expecting set values in the form of a single string like one two three
How to convert Set to String with spaces in javascript
Multiple ways we can convert Set to String with spaces
Array.from with join function
First , convert set into Array using Array.from() function
Array.from() method accepts set or any iterated array of objects and returns an array.
Next, Iterate resulted in array elements and use join function and return a string with spaces.
let result=Array.from(set).join(' ');
console.log('== ',result); // one two three
also, you can use [spread operator syntax] (/2018/08/es6-spread-operator-in-javascript.html) can be replaced with Array.from() as seen below
let result=[...set].join(' ');
console.log(result); // one two three
using for of loops
First, Iterate each element of set using for of loop add each element to result array finally using join function, return string
let result = [];
for(let str of set){
result.push(str);
}
console.log([...result].join(' '));
You can also check different ways to iterate enumerated objects in javascript to iterate each element in a set.
using foreach loop foreach loop is another to iterate a set. Here is an example for foreach set iteration.
let result='';
set.forEach(value => result =result+" "+ value);
console.log(result);
How to convert set to string comma separated
As discussed above, First, convert set to array using Array.from() function next, using join with comma, returns string with comma separated string
let result='';
result=Array.from(set).join(',');
console.log(result); // one,two,three
Conclusion
To Sum up, we can iterate each element in a set of many ways and convert it to an array and write a logic to get desired output.