How to convert Set to String space separated in javascript
- Admin
- Dec 31, 2023
- Javascript
There are many ways to convert Set to String with a space separator in javascript.
Set
is a data structure introduced in the latest javascript(ES6). It is used to store unique elements.
Next, Declare a set variable and add the data to it.
var set = new Set();
set.add("first");
set.add("second");
set.add("three");
As you see above, Set stores multiple strings.
It is not straightforward, to convert Set to String.
Set has toString() method which prints [Object Set]
console.log(set); //:[object Set]
console.log(set.toString()); //[object Set]
This is not what we are expecting. Instead, We want values from the set 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 a set or any iterated array of objects and returns an array.
Next, Iterate results in an array of elements and uses the join
function, and returns 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 S using for of loop
add each element to the result array finally, using join
function, return a 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 way to iterate a set. Here is an example of 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 the set to an array using Array.from()
function next, using a 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.