0
question related to an array in javascript
how to Write a function list that takes an array of words and returns a string by concatenating the words in the array, separated by commas and - the last word - by 'and'. An empty array should return an empty string. Example: list(['Huey', 'Dewey', 'Louie']) should return 'Huey, Dewey and Louie'.
2 ответов
+ 2
const list = arr => {
let str = ""
arr.forEach((val, i) => {
if (i === 0) {
str += val
} else if (i === arr.length - 1) {
str += " and " + val
} else {
str += ", " + val
}
})
return str
}
Ask if u dont understand a line,
I initialized a variable called "str" which is set to an empty string. On every iteration of the forEach loop, we have access to the element we are currently on, and the index of the element, so i checked if the index is 0 (i.e., the element is the first word), append the current word to the str variable without ", " and " and ". Otherwise if it is the last index, append the current value along with " and ", otherwise if it is not the first or the last word, then just use commas, ", " with the current word.
+ 1
let arr = [ 'Huey', 'Dewey', 'Louie' ];
function list( arg )
{
if( arg.length === 0 )
{
return ""; // empty array
}
else if( arg.length < 3 )
{
return `${ arg[0] } and ${ arg[1] }`; // only 2 words
}
// remove last word, and save it in <lastOne>
let lastOne = arg.pop( -1 );
// join the remaining words with ", "
// then put "and" before the <lastOne>
return `${ arg.join( ", " ) } and ${ lastOne } `;
}
console.log( list( arr ) );