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"...
To convert an array to a string with spaces, call the join() method on the array, passing it a string containing a space as a parameter - arr. join(' ') . The join method returns a string with all array elements joined by the provided separator. Copied!
Join Together an Array as a String with Commas. When you need to join together every item in a JavaScript array to form a comma-separated list of values, use . join(",") or equivalently just . join() without any arguments at all.
join method. To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.
Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.
One option would be to pop
the last item, then join
all the rest by commas, and concatenate with and
plus the last item:
const input = ['one', 'two', 'three', 'four']; const last = input.pop(); const result = input.join(', ') + ' and ' + last; console.log(result);
If you can't mutate the input array, use slice
instead, and if there might only be one item in the input array, check the length of the array first:
function makeString(arr) { if (arr.length === 1) return arr[0]; const firsts = arr.slice(0, arr.length - 1); const last = arr[arr.length - 1]; return firsts.join(', ') + ' and ' + last; } console.log(makeString(['one', 'two', 'three', 'four'])); console.log(makeString(['one']));
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