Krishnam
Krishnam

Reputation: 45

Add 'commas' separator between all array elements and 'and' before the last array element

I am trying to display array item of an array in a single line divided by 'commas' but the last array item should be preceded by 'and' and a full stop should be added at the end of the last element.

For example:

var cars = new Array("Saab", "Volvo", "BMW", "ZEST", "Audi");

Should be displayed as Saab, Volvo, BMW, ZEST and Audi.

var cars = new Array("Saab", "Audi");

If there are only 2 items then it should display as Saab and Audi.

var cars = new Array("Saab");

If there is only 1 item it should display as Saab.

The array length is dynamic but it should follow the above format i.e. all array item should be separated by commas but there should be 'and' between 2nd last array item and last array item.

var cars = new Array("Saab", "Volvo", "BMW", "ZEST", "Audi");

for (i = 0; i < cars.length; i++) {

  var total = cars.length;
  var lastbut = total - 1;
  var disp;
  var addand = "";


  if (i != cars.length - 1) {
    disp = ", "
  } else {
    addand = "and "
    disp = "."
  }


  document.write(addand + cars[i] + disp);

}

https://jsfiddle.net/f01ph8pa/2/

I am not able to complete this. Can you please help?

Upvotes: 1

Views: 1551

Answers (2)

Stuart
Stuart

Reputation: 9868

Use slice to get all but the last string in the array and join them with a comma; then add " and " and the final string in the array.

function listStrings(arr) {
  if (arr.length <= 1) {
    return arr[0] + ".";
  }
  return arr.slice(0, -1).join(", ") + " and " + arr.at(-1) + ".";
}

console.log(listStrings(['A', 'B', 'C', 'D']));
console.log(listStrings(['A', 'B']));
console.log(listStrings(['A']));

Upvotes: 6

VHS
VHS

Reputation: 10194

How about the following way? You join the array elements first with a comma and then replace the last comma with ' and '.

        var cars = new Array("Saab", "Volvo", "BMW", "ZEST", "Audi");
        var output = cars.join(",");
        output = output.replace(/,([^,]*)$/,' and '+'$1');
        console.log(output)

Upvotes: 1

Related Questions