In this article we will learn how to convert set to a string in JavaScript.
It is very common to convert set to a string in JavaScript in JavaScript.
Problem
Now we have a problem, which is that we want to convert the set into a string.
Imagine you have a Set like this:
const set = new Set([1, 2, 3, 4]);
And we want to convert it into a string.
How to solve this problem?
The solution to this problem is easy, but first we have to convert the Set into an array and then convert the array into a String using join
method.
Solution will be as follow:
- Convert set to an array using
Array.from
- Convert array to a string using
join
method
Convert set to a string
We can convert set to a string but first we need to convert set to an array.
// Set
const set = new Set([1, 2, 3, 4]);
// Convert to an array
const toArr = Array.from(set);
// Result:
console.log(toArr);
Output
[ 1, 2, 3, 4 ]
Then, we will convert this array into a string.
// Set
const set = new Set([1, 2, 3, 4]);
// Convert to an array
const toArr = Array.from(set);
// Convert to a string
const result = toArr.join(' ');
// Result:
console.log(result);
Output
1 2 3 4
If you want to add separator between each element you can do this:
// Set
const set = new Set([1, 2, 3, 4]);
// Convert to an array
const toArr = Array.from(set);
// Convert to a string with separator
const result = toArr.join('-_-');
// Result:
console.log(result);
Output
1-_-2-_-3-_-4
Thank you for reading
Thank you for reading my blog. 🚀