I want to convert the array ['one', 'two', 'three', 'four']
into one, two, three and four
Note that the first items have a comma, and but there is the word and
between the second-last one and the last one.
The best solution I've come up with:
a.reduce( (res, v, i) => i === a.length - 2 ? res + v + ' and ' : res + v + ( i == a.length -1? '' : ', '), '' )
It's based on adding the commas at the end -- with the exception of the second-last one (a.length - 2
) and with a way to avoid the last comma (a.length - 2
).
SURELY there must be a better, neater, more intelligent way to do this?
It's a difficult topic to search on search engines because it contains the word "and"...
one, two, three, and four
?