Help with 'Title Case a Sentence' algorithm challenge

Help with 'Title Case a Sentence' algorithm challenge
0

#1

Hi, please could someone help explain this code to me. I tried many different possible solutions and didn’t quite get there so checked the basic solution. I know that map() calls a function for each element in convertToArray and creates a new array with the results, but I’m not sure what part the (val) argument plays in this? …putting it in a very dumb and literal sense, how does the code know what (val) is referring to (if that makes sense)?

function titleCase(str) {
  var convertToArray = str.toLowerCase().split(" ");
  var result = convertToArray.map(function(val){
      return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
  });
  return result.join(" ");
}

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

#2

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

val represents the current element being iterated over in the map callback function. The map method iterates over the array applying the callback function each time. The first argument (in this case val) represents the current element, the second argument (not used in your code) represents the index of the current element, and a third argument (not used in your code) represents the actual array being iterated over.

Below is an example of using all three arguments. I have put console.log statements in, so you can see what the value of each is during the execution of the code.

var arr = [10, 20, 30,  40];
var multipliedBy10 = arr.map(function(currElem, currElemIndex, currArray) {
  console.log(currElem);
  console.log(currElemIndex);
  console.log( currArray);
  return currElem * 10;
});
console.log(multipliedBy10); 

Below is what is displayed to the browser’s console on execution:

10
0
[ 10, 20, 30, 40 ]
20
1
[ 10, 20, 30, 40 ]
30
2
[ 10, 20, 30, 40 ]
40
3
[ 10, 20, 30, 40 ]
[ 100, 200, 300, 400 ]


#3

That’s great, thanks so much for the explanation and my apologies for including the solution (d’oh!). I’ll bear that in mind for future posts!