Sunday, May 23, 2021

Javascript Practice 59: JS Hero - Array: join()

 
Question: 

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 an 'and'. An empty array should return an empty string.

Example: list(['Huey', 'Dewey', 'Louie']) should return 'Huey, Dewey and Louie'.




Answer: 

function list (array) {

if (array.length === 0) {

return ''; } else if (array.length === 1) {

return array[0]; } else { 

let wordsExLast = array.slice(0, array.length - 1); 
let lastWord = array[array.length-1]; 
return wordsExLast.join(', ') + ' and ' + lastWord;
}; 

};





> we create a function declaration 'list'
> it has a parameter array
> we then open if / else if / else statements
> the first condition is to check if the array length is 0
> if it is 0 then the function should return an array which is empty
> else if the length of the array has only one word then the function should return just that element
> or else the function should do the following: 
>>> create a variable wordsExLast
>>> it should contain all the elements of the array except the last word
>>> we use the slice method to return a shallow copy of the array without the last word
>>> like this: array.slice(0, array.length - 1)
>>> create another variable lastWord
>>> this variable is to store the returned word when we access the last word of the array
>>> we then concatenate and join the two variables - wordsExLast & lastWord
>>> wordsExLast.join(',') + 'and' + lastWord

No comments:

Post a Comment