Using a recursive function to capitalize each word in an array in JavaScript


We are required to write a JavaScript function that takes in an array of String literals. The function should do the following two things −

  • Make use of recursive approach

  • Make first word of each string element capital.

Our function should do this without using extra space for storing another array.

For example −

If the input array is −

const arr = ['apple', 'banana', 'orange', 'grapes'];

Then the array should be transformed to −

const output = ['Apple', 'Banana', 'Orange', 'Grapes'];

Example

The code for this will be −

const arr = ['apple', 'banana', 'orange', 'grapes'];
const capitalize = (arr = [], ind = 0) => {
   const helper = (str = '') => {
      return str[0].toUpperCase() + str.slice(1).toLowerCase();
   };
   if(ind < arr.length){
      arr[ind] = helper(arr[ind]);
      return capitalize(arr, ind + 1);
   };
   return;
};
capitalize(arr);
console.log(arr);

Output

And the output in the console will be −

[ 'Apple', 'Banana', 'Orange', 'Grapes' ]

Updated on: 23-Nov-2020

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements