Reputation: 366
I need to know how I can split an array with commas and if it's the last one element to the last one I have , and
and if it's the last one I add .
to it. I have the following code. The output as one big string honda, audi, tesla, and toyota.
the following is printing more than one. Also what if I wanted to push it one time into new array. So one big array of string ["honda, audi, tesla, and toyota."]
let namesArray = ["honda", "audi", "tesla", "toyota"];
let newOrder = ""
namesArray.forEach((item, index) => {
console.log(index);
if (index === namesArray.length - 2) {
newOrder = item + ' , and'
} else if (index === namesArray.length - 1) {
newOrder = (item + '.')
} else {
newOrder = (item + ',')
}
})
console.log('new string ', newOrder)
"new string ", "honda,audi,tesla,toyota."
Upvotes: 0
Views: 2066
Reputation: 10617
I would create a function for reuse. First make a .slice()
of your array, so the original is not affected. .pop()
off the last Array element. Then .join(', ')
and concatenate +', and '
along with the element you popped off +'.'
.
function andIt(array){
const a = array.slice(), p = a.pop()+'.';
if(!a.length){
return p;
}
return a.join(', ')+', and '+p;
}
const namesArray = ['honda', 'audi', 'tesla', 'toyota'];
console.log(andIt(namesArray)); console.log(andIt(['test']));
Upvotes: 0
Reputation: 25401
You can easily achieve this result using map and join
const arr = ["honda", "audi", "tesla", "toyota"];
const result = arr
.map((item, index) => {
if (index === arr.length - 1) {
return `and ${item}.`;
} else {
return `${item}, `;
}
})
.join("");
console.log(result);
You can also use string template literal if the array size in known prior
const arr = ["honda", "audi", "tesla", "toyota"];
const [a, b, c, d] = arr;
const result = `${a}, ${b}, ${c}, and ${d}.`;
console.log(result);
Upvotes: 2
Reputation: 147276
In terms of what is wrong with your existing code, you are not adding the new string value to your output (i.e. use newOrder +=
, not newOrder =
in the loop):
let namesArray = ["honda", "audi", "tesla", "toyota"];
let newOrder = ""
namesArray.forEach((item, index) => {
if (index === namesArray.length - 2) {
newOrder += item + ', and '
} else if (index === namesArray.length - 1) {
newOrder += (item + '.')
} else {
newOrder += (item + ', ')
}
})
console.log(newOrder)
It would be simpler though to just join
a slice
of the array from the start to the second to last element, then add , and
and the last element to that string:
let namesArray=["honda", "audi", "tesla", "toyota"];
let newOrder = namesArray.slice(0,-1).join(', ') + ', and ' + namesArray.slice(-1) + '.';
console.log(newOrder)
Upvotes: 4