Here's a simple, IE6 (and potentially earlier) backwards-compatible solution without filter
.
TL;DR → look at the 3rd-last block of code
toString()
has a habit of turning arrays into CSV and ignore everything that is not a string, so why not take advantage of that?
["foo", null, "bar", undefined, "baz"].toString()
→ foo,,bar,,baz
This is a really handy solution for straightforward CSV data export use cases, as column count is kept intact.
join()
has the same habit but let's you choose the joining delimiter:
['We built', null, 'this city', undefined, 'on you-know-what'].join(' ')
→ We built this city on you-know-what
As the OP asking for a nice space after the comma and probably don't like the extra commas, they're in for a replace
-RegEx treat at the end:
["foo", null, "bar", undefined, "baz"].join(', ').replace(/(, ){2,}/g, ', ')
→ foo, bar, baz
Caveat: (, ){2,}
is a rather simple RegEx matching all 2+ occurrences of commas followed by a space – it therefore has the potentially unwanted side-effect of filtering any occurrences of , ,
or ,
at the start or end of your data.
Of that is no concern, you're done here with a neat and simple, backwards-compatible one-liner.
If that is a concern, we need come up with a delimiter that is so far-out that the probability of it appearing twice in your data items (or once at the beginning or the end) approaches zero. What do you think about, for instance, crazy-ſđ½ł⅞⅝⅜¤Ħ&Ł-delimiter
?
You could also use literally any character, probably even ones that don't exist in your local charset, as it is just a stop-signifier for our algorithm, so you could do:
["foo", null, "bar", undefined, "baz"]
.join('emoji-✊-delimiter')
.replace(/(emoji-✊-delimiter){2,}/g, ', ')
or (in a more DRY version of this:
var delimiter = 'emoji-✊-delimiter'
var regEx = new RegExp('(' + delimiter + '){2,}', 'g')
["foo", null, "bar", undefined, "baz"].join(delimiter).replace(regex, ', ')