The browser storage localStorage is not available. Either your browser does not support it or you have disabled it or the maximum memory size is exceeded. Without localStorage your solutions will not be stored.
Array: join()
With
join
you join all elements of an array into a string:
let words = ['Sex', 'Drugs', 'Rock', 'Roll'];
let s1 = words.join();
let s2 = words.join(' & ');
let s3 = words.join(' and ');
Without an argument join
joins the elements separated by commas.
s1
has the value 'Sex,Drugs,Rock,Roll'
.
Otherwise, the passed argument specifies the separator.
s2
has the value 'Sex & Drugs & Rock & Roll'
and
s3
has the value 'Sex and Drugs and Rock and Roll'
.Exercise
Write a function
Example:
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'
.
+ Hint
Create a new array without the last element. Join the elements of this new array with a comma.
Append the last element of the original array. Handle edge cases separately.
+ Solution
function list(words) {
if (words.length === 0) {
return '';
}
if (words.length === 1) {
return words[0];
}
let wordsExLast = words.slice(0, words.length - 1);
let lastWord = words[words.length - 1];
return wordsExLast.join(', ') + ' and ' + lastWord;
}