How to convert Set to String space separated in javascript


There are many ways to convert Set to String with space separatro 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 striaignforward.

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 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 array lements and use join function and return 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 an set. Here is 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 set many ways and convert to array and write a logic to get desired output

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.