I'm having issues to convert a Set to a comma 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?
It 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 comma at the end as well.
To avoid this, you have two ways:
Remove the last comma 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 comma 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, ','));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With