I'm having issues to convert a Set
to a ma separated string
in IE11, the below works fine in chrome, but IE11 doesn't like Array.from
.
let a = new Set();
a.add("a");
a.add("b");
console.log(Array.from(a).join(","));
To get a work around I'm doing:
let aArray = [];
let pushToArray = function(val) {
aArray.push(val);
};
a.forEach(pushToArray);
console.log(aArray.toString());
Any suggestion on how to do the above better that works in IE11?
I'm having issues to convert a Set
to a ma separated string
in IE11, the below works fine in chrome, but IE11 doesn't like Array.from
.
let a = new Set();
a.add("a");
a.add("b");
console.log(Array.from(a).join(","));
To get a work around I'm doing:
let aArray = [];
let pushToArray = function(val) {
aArray.push(val);
};
a.forEach(pushToArray);
console.log(aArray.toString());
Any suggestion on how to do the above better that works in IE11?
Share Improve this question edited Feb 17, 2020 at 19:12 Somebody asked Feb 17, 2020 at 19:03 SomebodySomebody 2,78914 gold badges66 silver badges104 bronze badges 1- Looks like you found a valid workaround already. What about it doesn't work for you? See developer.mozilla/en-US/docs/Web/JavaScript/Reference/… for info on what functions of your Set you can use if you have to support IE11. – TimoStaudinger Commented Feb 17, 2020 at 19:07
2 Answers
Reset to default 5It could be better, if you don't even build an array from it, only create the string using concatenation:
let a = new Set();
a.add("a");
a.add("b");
function SetToString(set, delim){
let str = '';
set.forEach(function(elem){
str += elem + delim
});
return str
}
console.log(SetToString(a, ','));
The only issue with this approach is that it will add a ma at the end as well.
To avoid this, you have two ways:
Remove the last ma using
.slice(0, -1)
let a = new Set(); a.add("a"); a.add("b"); function SetToString(set, delim){ let str = ''; set.forEach(function(elem){ str += elem + delim }); return str.slice(0, -1) } console.log(SetToString(a, ','));
Count elements, and omit ma for the last
let a = new Set(); a.add("a"); a.add("b"); function SetToString(set, delim){ let str = ''; let i = 0; let size = set.size; set.forEach(function(elem){ str += elem if(i++ < size - 1) str += delim }); return str } console.log(SetToString(a, ','));
This question is the first hit on google now when searching for javascript join set with ma
(and likely other, similar queries).
If you're here because you want to do this and don't care about IE11 anymore, read the question again carefully. The easy way is:
const maSeparatedString = Array.from(new Set(['a', 'b', 'a'])).join(", ")
console.log(maSeparatedString)
// => "a, b"
Note: This is not the correct answer to the initial question, just a headsup for those seeking an answer to what google thinks they are looking for. The answer from @FZs should still be the accepted answer!