Join an array by commas and "and"

Viewed 14259

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"...

9 Answers

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

Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat API. It will also take care of localizing your list when requested, which might be of great help if you need it.

const lf = new Intl.ListFormat('en');

console.log(lf.format(['Frank']));
// → 'Frank'

console.log(lf.format(['Frank', 'Christine']));
// → 'Frank and Christine'

console.log(lf.format(['Frank', 'Christine', 'Flora']));
// → 'Frank, Christine, and Flora'

console.log(lf.format(['Frank', 'Christine', 'Flora', 'Harrison']));
// → 'Frank, Christine, Flora, and Harrison'

// You can use it with other locales
const frlf = new Intl.ListFormat('fr');

console.log(frlf.format(['Frank', 'Christine', 'Flora', 'Harrison']));
// → 'Frank, Christine, Flora et Harrison'

You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".

It's not very widely supported as of writing, so you might not want to use it everywhere.

References
The Intl.ListFormat API - Google Developers
V8 release v7.2

I like Mark Meyer's approach as it doesn't alter the input. Here's my spin:

const makeCommaSeparatedString = (arr, useOxfordComma) => {
  const listStart = arr.slice(0, -1).join(', ')
  const listEnd = arr.slice(-1)
  const conjunction = arr.length <= 1 
    ? '' 
    : useOxfordComma && arr.length > 2 
      ? ', and ' 
      : ' and '

  return [listStart, listEnd].join(conjunction)
}

console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']))
// one, two, three and four

console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true))
// one, two, three, and four

console.log(makeCommaSeparatedString(['one', 'two'], true))
// one and two

console.log(makeCommaSeparatedString(['one']))
// one

console.log(makeCommaSeparatedString([]))
//

You can use Array.prototype.slice() when array.length is bigger than 1 and exclude the rest of the cases:

const result = a => a.length > 1 
  ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` 
  : {0: '', 1: a[0]}[a.length];

Code example:

const input1 = ['one', 'two', 'three', 'four'];
const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const input3 = ['one', 'two'];
const input4 = ['one'];
const input5 = [];

const result = a => a.length > 1 
  ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` 
  : {0: '', 1: a[0]}[a.length];

console.log(result(input1));
console.log(result(input2));
console.log(result(input3));
console.log(result(input4));
console.log(result(input5));

Using Array#reduce:

['one', 'two', 'three', 'four'].reduce( (a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)

Another approach could be using the splice method to remove the last two elements of the array and join they using the and token. After this, you could push this result again on the array, and finally join all elements using the , separator.


Updated to:

1) Show how this works for multiple cases (no extra control needed over the array length).

2) Wrap the logic inside a method.

3) Do not mutate the original array (if not required).

let arrayToCustomStr = (arr, enableMutate) =>
{
    // Clone the received array (if required).
    let a = enableMutate ? arr : arr.slice(0);

    // Convert the array to custom string.
    let removed = a.splice(-2, 2);
    a.push(removed.join(" and "));
    return a.join(", ");
}

// First example, mutate of original array is disabled.
let input1 = ['one', 'two', 'three', 'four'];
console.log("Result for input1:" , arrayToCustomStr(input1));
console.log("Original input1:", input1);

// Second example, mutate of original array is enabled.
let input2 = ['one', 'two'];
console.log("Result for input2:", arrayToCustomStr(input2, true));
console.log("Original input2:", input2);

// Third example, lenght of array is 1.
let input3 = ['one'];
console.log("Result for input3:", arrayToCustomStr(input3));

// Fourth example, empty array.
let input4 = [];
console.log("Result for input4:", arrayToCustomStr(input4));

// Plus example.
let bob = [
    "Don't worry about a thing",
    "Cause every little thing",
    "Gonna be all right",
    "Saying, don't worry about a thing..."
];
console.log("Result for bob:", arrayToCustomStr(bob));
.as-console-wrapper {
    top: 0px;
    max-height: 100% !important;
}

Intl.ListFormat is exactly what you want. Although only Chrome 72+ and Opera 60+ are supported in May, 2019, a polyfill is available for other browsers: https://github.com/zbraniecki/IntlListFormat

const list = ['A', 'B', 'C', 'D'];

// With Oxford comma 
const lfOxfordComma = new Intl.ListFormat('en', {
  style: 'long',
  type: 'conjunction'
});
console.log(lfOxfordComma.format(list)); // → A, B, C, and D


// Without Oxford comma 
const lfComma = new Intl.ListFormat('en-GB', {
  style: 'long',
  type: 'conjunction'
});
console.log(lfComma.format(list)); // → A, B, C and D

Here's a one-line option that is similar to Yosvel Quintero Arguelles's answer but provides an Oxford comma when there are three or more items.

let resultA4 = (list => list.length < 3 ? list.join(" and ") : [list.pop(), list.join(", ")].reverse().join(", and ")).call(this, ['one', 'two', 'three', 'four']);

let resultA2 = (list => list.length < 3 ? list.join(" and ") : [list.pop(), list.join(", ")].reverse().join(", and ")).call(this, ['one', 'two']);

let resultA1 = (list => list.length < 3 ? list.join(" and ") : [list.pop(), list.join(", ")].reverse().join(", and ")).call(this, ['one']);

let items = ['one', 'two', 'three', 'four'];

//If you can't mutate the list you can do this
let resultB = (list => list.length < 3 ? list.join(" and ") : [list.pop(), list.join(", ")].reverse().join(", and ")).call(this, items.slice());

// or this option that doesn't use call
let resultC = items.length < 3 ? items.join(" and ") : [items.slice(0, -1).join(", "), items.slice(-1)].join(", and ");

console.log(resultA4);
console.log(resultA2);
console.log(resultA1);
console.log(resultB);
console.log(resultC);

An easy way is also to insert and before the last word or quoted string using regex. Answer here on stack overflow

Related