Title Case a Sentence: cascading methodes

Hello,
My code works so I add spoiler tags.
Tehe link to the exercice:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence


function titleCase(str) {
  let minStr = str.toLowerCase();
  let tabWords = minStr.split(' ')
  console.log(tabWords)
  let result = [];
  for (let i = 0; i < tabWords.length; i++) {
    let firstLetter = tabWords[i][0].toUpperCase();
    let tword = tabWords[i].split('')
    tword.splice(0, 1, firstLetter)
    tword = tword.join('');
    result.push(tword);
    console.log(result)
  }
  return result.join(' ')
 
}

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

In regard to this lines:

  let tword = tabWords[i].split('')
    tword.splice(0, 1, firstLetter)
    tword = tword.join('');

Why is not possible to do that ?

 let tword = tabWords[i].split('').splice(0, 1, firstLetter).join('');

splice deletes what you specify from the array and returns that (in an array, so the join will still work), which I think is not what you want.

1 Like

If I break down:
1)

tabWords[i].split('')   //  I made a table.
.splice(0, 1, firstLetter)  //  I delete 0 index, but I replace it by the variable "firstLetter",
//I don't understand why I have to change of line.

Why I have to change of line ?

 let tword = tabWords[i].split('')
    tword.splice(0, 1, firstLetter)
join('')  //  I transform the table into string.

If I made:

 let tword = tabWords[i].split('')
    tword.splice(0, 1, firstLetter)
    tword.join('');    //  Doesn't work

Why I have to write this ?

tword = tword.join('');

As I said, splice deletes whatever you specify, and it returns what you deleted. If you deleted the first item, that’s what it returns. The splice function returns an array, so you can run join in that just fine, but that array only contains that item you deleted – you are saying “delete one item in the array tword at index 0 and replace it with whatever firstLetter is”.

You want to run join on the array you modified (tword), not the return value of the splice operation

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