Join an array by commas and “and”

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 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;

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']));

Leave a Reply

Your email address will not be published. Required fields are marked *