So I am doing an algorithm challenge where I am given an array of words and I must capitalize the first letter of the word and return the arr with the new words. it must be done with recursion. I believe my approach is wrong, but if it's conceptually please let me know and how I should be thinking about this. If anyone could help describe how I should be approaching this both conceptually and in code it would be really helpful.
To describe my idea of how this is working conceptually:
1st call: ['Car'] + capitalizeFirst([taco, banana]);
2nd call: ['Taco'] + capitalizeFirst([banana]);
3rd call: ['Banana'] + capitalizeFirst(['']);
so then as it walks back it returns
['Banana'] + ['""']
['Taco'] + ['Banana']
['Car'] + ['Taco','Banana']
returns ['Car','Taco','Banana']
but what I Am getting is 'CarTacoBanana'.
here is the approach I took.
function capitalizeFirst (arr) {
if (!arr.length) return '';
arr[0] = arr[0].charAt(0).toUpperCase() + arr[0].slice(1);
return [ arr[0] + capitalizeFirst(arr.slice(1)) ];
}
capitalizeFirst(['car','taco','banana']); // ['Car','Taco','Banana']
(edit) I was able to solve my approach was wrong! here was my solution
let newArr = [];
if (!arr.length) {
return newArr;
}
else {
arr[0] = arr[0].charAt(0).toUpperCase() + arr[0].slice(1);
newArr.push(arr[0]);
}
console.log(newArr, 'test');
return newArr.concat(capitalizeFirst(arr.slice(1)))
// return newArr;