Search code examples
javascriptarraysalgorithmrecursioncapitalize

Write a recursive function called capitalizeFirst. Given an array of strings, capitalize the first letter of each string in the array


I see this similar algorithm was posted on stackoverflow, nevertheless I cannot understand, so I decided to post once more.

function capitalizeFirst(arr) {
  if (arr.length === 1) {
    return [arr[0].toUpperCase()]
  }
  let res = capitalizeFirst(arr.slice(0, -1))
  res.push(arr.slice(arr.length - 1)[0].toUpperCase())
  return res
}

console.log(capitalizeFirst(['dog', 'car', 'horse']))

Things I do not understand...

  1. Why it is inside square brackets return [arr[0].toUpperCase()] why not just return arr[0].toUpperCase()
  2. Why "arr" is getting sliced twice:

here

let res = capitalizeWords(arr.slice(0,-1)

and here

res.push(arr.slice(arr.length-1)[0].toUpperCase())

Overall, I am lost, please help


Solution

  • I would forget about what that code does and concentrate on the steps you need to take to make your function work.

    1. Recursive - so the function needs to call itself but you need to find a way to identify which element you're working on.

    2. You need a way to break out of the recursion when you reach the end of the array.

    3. You need a way to separate out the first letter of an element from all the rest, and update the element with a transformed string.

    Here's how I might approach it.

    // Pass in the array, and initialise an index
    // variable
    function capitalizeFirst(arr, index = 0) {
      
      if (!arr.length) return 'Empty array';
    
      // If we're at the end of the array
      // return the array
      if (index === arr.length) return arr;
      
      // If the element is not empty
      if (arr[index].length) {
      
        // Get the first letter, and place all
        // the other letters in an array called `rest`
        // You can use destructuring here because strings
        // are iterable
        const [first, ...rest] = arr[index];
    
        // Update the element at the current index
        // with the new string making sure you join up `rest`
        arr[index] = `${first.toUpperCase()}${rest.join('')}`;
      
      }
    
      // Call the function again increasing the index
      return capitalizeFirst(arr, ++index);
    }
    
    console.log(capitalizeFirst(['dog', 'car', 'horse']));
    console.log(capitalizeFirst([]));
    console.log(capitalizeFirst(['dog', '', 'horse']));
    console.log(capitalizeFirst(['dog', 'o', 'horse']));

    Additional documentation