Help: title case sentence using nested for loop

I solved problem in normal procedure method using nested for loops.
I am getting space between letters not words.
but we need space between words to pass the test.
Question link below:

function titleCase(str) {
  let arr = str.toLowerCase().split(' ');
  let final = [];
  for(let i=0; i<arr.length; i++){
      final.push(arr[i][0].toUpperCase());
      for(let j=1; j<arr[i].length; j++){
        final.push(arr[i][j].toLowerCase());
      }
  }
  return final.join('');
}

console.log(titleCase("I'm a little tea pot"));

my final output: I’mALittleTeaPot

To add space between each word, you’ll need to append an empty space to your final array after the nested for loop

....
....
for(let j=1; j<arr[i].length; j++){
        final.push(arr[i][j].toLowerCase());
}
final.push(" ")     // ---> Just add this
....
....
1 Like
      for(let j=1; j<arr[i].length; j++){
        final.push(arr[i][j].toLowerCase());
      }

The issue is in your second for loop.

Take another look and you will see that you are pushing each letter to the array, one at a time. There are no spaces between the different indexes of the array. The array then gets joined together and you get a string with no spaces.

Try using one final.push and concatenate the uppercase first letter with the rest of the array.

Something like this could work:

arr[i][0].toUpperCase() + arr[i].slice(1);
1 Like

thank you @iamprinx , Excellent solution.
I thought that my method of solving was wrong, and
I have to change it to another method.

I added the code and answer mentioned on the console
is correct but when i run the code tests are not passing
I am not able to understand

Yes you are right @c0deblack my second for loop is pushing
single letter each time. By the using this method
arr[i][0].toUpperCase() + arr[i].slice(1);
i got the answer with all tests passing
Thank you.

I added the code and answer mentioned on the console
is correct but when i run the code tests are not passing
I am not able to understand

This can be resolve by trimming off excess spaces from string .

return final.join('').trim();
1 Like

Thank you so much @iamprinx
It is working with all tests passed: amazing

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.