Why use .push? Title Case a Sentence

Why use .push? Title Case a Sentence
0

#1

This is a solution to upper-casing the first letter of each word in a sentence. The solution works, but I am wondering why a simpler solution did not.

function titleCase(str) {
  var newArray = [];
  var array = str.toLowerCase().split(' ');
  for (var i = 0; i < array.length; i++) {
    newArray.push(array[i].replace(array[i][0], array[i][0].toUpperCase()));
  }
  return newArray.join(' ');
}

In this solution I pushed to a new array with each iteration of the loop. I am wondering why I am not able to just alter the array directly. For example, by having the following in the loop instead:

array[i] = array[i].replace(array[i][0], array[i][0].toUpperCase());

and by doing so dropping the need for a newArray. Why does this approach not work?


#2

Can you post the entire alternative code? Also the test case that fails


#3

It should work, as long as you use array.join(" “) and not newArray.join(” "). Like @ppc, was there a specific test you were failing with this alternate solution? Also, does you function actually return for the specific test case?


#4

Thank you for the reply - I’ve re-written the code and it works now! There must have been a typo/ mistake somewhere. This is the new code:

function titleCase(str) {
  var array = str.toLowerCase().split(' ');
  for (var i = 0; i < array.length; i++) {
    array[i] = array[i].replace(array[i][0], array[i][0].toUpperCase());
  }
  return array.join(' ');
}

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

EDIT:

I am now aware it is better to use charAt() instead of indexing a string due to compatibility issues:

array[i].charAt(0), array[i].charAt(0).toUpperCase()

instead of:

array[i][0], array[i][0].toUpperCase()