How to human-join an array in JavaScript

Posted . Visible to the public.

To simulate Rails' to_sentence in your JavaScript application, you can use these few lines of CoffeeScript code:

joinSentence = (array) ->
  if array.length > 1
    array[0..-2].join(', ') + ', and ' + array[-1..]
  else
    array.join ', '

Examples:

> joinSentence(['cats', 'dogs', 'pandas'])
# => 'cats, dogs, and pandas'

^
> joinSentence(['llamas'])
# => 'llamas'

Here is some plain JavaScript, should you prefer that:

function joinSentence(array) {
  if (array.length > 1) {
    return array.slice(0, -1).join(', ') + ', and ' + array.slice(-1);
  } else {
    return array.join(', ');
  }
};
Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2016-08-30 13:50)