Almost there, but not understanding why my code won’t work. Looking for guidance as always.
Instructions:
Write a function named toSentence that takes an array and returns a string with the elements joined by commas, with a trailing 'and'
Example:
If you pass ["Sue", "Will"] it should return "Sue and Will"
If you pass ["Sue", "Will", "Rachel"] it should return "Sue, Will and Rachel"
function toSentence(arr) {
let str = '';
for (let i = 0; i < arr.length; i++) {
if (!arr[i].length - 1){
str += arr[i] + ', '
} else if (arr[i].length - 1){
str += ' and ' + arr[i]
} else {
return str;
}
}
return str;
};
I don’t understand why you are checking if the last element is a comma? I just don’t understand how that goes through. Doesn’t .length return a number?
yes .length returns a number. You are trying to add commas to your ‘str’ string in your if statement. But how does if (!arr[i].length - 1) check your array to see if you need to add commas to your string?
It basically means grab the last letter index of each word and negate it. so It’s something like
No prob bro. I actually gave you a wrong condition in the if statement too lol. To explain my point, take a look at this if statement.
if (arr[i][arr[i].length - 1] === ",")
You are running a forloop to check every word in the array. If a word meets certain conditions, you want to add its word and comma to the string. So what should I be looking for in each word to add its word and comma to the string?
You can simply check if each the last element of each word is a comma and that is what the above code does.
I’m sure I could solve it this way, but that makes even more code, right? Ideally, I would like to keep it the same length or just a bit shorter if possible. Certainly there is a way without checking if there are only 2 in the array?
Let’s do this concise way like your first attempt.
In your for loop, I would have 3 conditions.
First condition is to check if you are at the last element. Then Just add " and " before adding the last word.
Second condition is to check if it’s the 2nd last word. If then, don’t add the comma. Just add the word to the string
Last is else condition. If above conditions are not satisfied, just keep adding the words with comma after.
Give it a try, if you can’t still figure it out check out my solution below.
Summary
function toSentence(arr) {
let str = '';
for (let i = 0; i < arr.length; i++) {
if (arr.length - 1 === i){
str += ' and ' + arr[i]
} else if (arr.length - 2 === i){
str += arr[i]
} else {
str += arr[i] + ', '
}
}
return str;
};
//toSentence(["Sue", "Will"]); // Sue and Will
toSentence(["Sue", "Will", "Rachel"]); // "Sue, Will and Rachel"