snowflakes74 snowflakes74 - 1 month ago 7
Javascript Question

Conditional array.join in Javascript

I have an array of strings and I would like to display them as a comma separated string but add "and" for the last element. For example I have

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(' ,');


outputs

'Banana, Orange, Apple, Mango'


Is there any way the I add "and" for the last word so it outputs

'Banana, Orange, Apple and Mango'

Answer

You can try this,

var delimitter = ', ';
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(delimitter); 
var index = energy.lastIndexOf(delimitter);
energy = energy.substring(0, index) + ' and ' + energy.substring(index + delimitter.length);

console.log(energy);