[Solved] Javascript comma list but has an and at the last one


This should work.

function createSentence(array) {
  if (array.length == 1) {
    return array[0];
  } else if (array.length == 0) {
    return "";
  }
  var leftSide = array.slice(0, array.length - 1).join(", ");
  return leftSide + " and " + array[array.length - 1];
}

console.log(createSentence(["dogs", "cats", "fish"]));
console.log(createSentence(["dogs", "cats"]));
console.log(createSentence(["dogs"]));
console.log(createSentence([]));

6

solved Javascript comma list but has an and at the last one