Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The most efficient way to convert a javascript set to string

Is there a way of converting a Set to a String directly (without first converting the set to an array)? I have gone through the documentation at Mozilla and I feel they may be a way of doing it. This is what I do:

let myset = new Set();
myset.add(3);
myset.add(" Wise ");
myset.add(" Men ");

let setStr = myset.toString();
let setArrStr = Array.from(myset).toString();

console.log("Set to String: " + setStr );  //"Set to String: [object Set]"
console.log("Set to Array to String: " + setArrStr);  // "Set to Array to String: 3, Wise , Men "
like image 906
Nditah Avatar asked Aug 31 '25 22:08

Nditah


1 Answers

You can convert to string directly like so:

let string = "";
let myset = new Set();
myset.add(3);
myset.add(" Wise ");
myset.add(" Men ");

myset.forEach(value => string += value);
console.log(string); // → "3 Wise  Men "

Hope you got your answer.

like image 77
theAlexandrian Avatar answered Sep 03 '25 16:09

theAlexandrian