Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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' ]
Advertisements
