Title Case a Sentence - printing only one element

Title Case a Sentence - printing only one element
0.0 0

#1

Hi Campers!
I am struggling with this basic algorithm challenge that asks me to capitalize the first letter of each element of the string.

This is my code so far, but the console only returns the first element of the array. If I move the return statement outside of the for loop, it returns the last element of the array, so I assume the loop is working correctly.

Could you point me in the right direction on why my code does not print the entire array?

function titleCase(str) {
  var newArray = [];
  //lower case everything and then turn the string in an array
  var lowerCase = str.toLowerCase().split(" "); 
    for (var i = 0; i < lowerCase.length; i++) {
   newArray = lowerCase[i].replace(lowerCase[i][0], lowerCase[i][0].toUpperCase());
    return newArray;
  }
  
}

titleCase("HERE IS MY HANDLE HERE IS MY SPOUT");

Link to the challenge:

Thanks


#2

In the loop, do newArray.push(yourModifiedWord). That will gradually build up the array. Then outside of the loop, return newArray. At the minute, you’re assigning the first word to the variable newArray, then immediately returning it, so the function exits at that point.

There’s still some work you’ll need to do to get it working properly after that, but it should give you a good start.

You have the right idea, but think of it like: you create an empty container. Then you loop through your words, modifying each in turn an putting them in the container. Then once that loop finishes, you can return the now-full container.


#3

Thank you so much, @DanCouper!

This is my final code, which worked! :slight_smile:

function titleCase(str) {
var newArray = [];
//lower case everything and then turn the string in an array
var lowerCase = str.toLowerCase().split(" “);
for (var i = 0; i < lowerCase.length; i++) {
newArray.push(lowerCase[i].replace(lowerCase[i][0], lowerCase[i][0].toUpperCase()));
}
return newArray.join(” ");
}
titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”);