Capitalize The First Letter Of Each Word In JavaScript Array

To capitalize the first letter of each word in JavaScript array, you can use the map() method. This method returns a new array with the results of calling a function for each element in the array. In this case, you would use the map() method to call a function that capitalizes the first letter of each word in an array, and then return the new array.

capitalize the first letter of each word in javascript array

map() Method To Capitalize The First Letter Of Each Word In JavaScript Array

var arr = ["this", "is", "a", "test"];

function capitalizeFirstLetter(word) {

  return word.charAt(0).toUpperCase() + word.slice(1);

}

var newArr = arr.map(capitalizeFirstLetter);

console.log(newArr); // ["This", "Is", "A", "Test"]

As you can see from the example above, the map() method calls the capitalizeFirstLetter() function for each element in the array, and then returns a new array with the results. This is a great way to manipulate arrays in JavaScript.

Another method you could use to achieve the same result is the forEach() method. This method calls a function for each element in an array, but does not return a new array.

forEach() Method To Capitalize The First Letter Of Each Word In JavaScript Array

var arr = ["this", "is", "a", "test"];

var newArr = [];

function capitalizeFirstLetter(word) {

  newArr.push(word.charAt(0).toUpperCase() + word.slice(1));

}

arr.forEach(capitalizeFirstLetter);

console.log(newArr); // ["This", "Is", "A", "Test"]

As you can see, the forEach() method is similar to the map() method, except that it does not return a new array. Instead, it calls the function for each element in the array and pushes the results into a new array.

You can also use the reduce() method to achieve the same result. This method applies a function to each element in an array, and returns a single value. In this case, you would use the reduce() method to call a function that capitalizes the first letter of each word in an array, and then return the resulting array.

reduce Method To Capitalize The First Letter Of Each Word In JavaScript Array

var arr = ["this", "is", "a", "test"];

function capitalizeFirstLetter(result, word) {

   result.push(word.charAt(0).toUpperCase() + word.slice(1));

   return result;

}

var newArr = arr.reduce(capitalizeFirstLetter, []);

console.log(newArr); // ["This", "Is", "A", "Test"]

As you can see, the reduce() method is similar to the map() and forEach() methods, except that it returns a single value. In this case, it returns an array with the results of calling the function for each element in the original array.

Conclusion

In this article, we looked at three different ways to capitalize the first letter of each word in an array in JavaScript. We looked at the map() method, the forEach() method, and the reduce() method. All three methods are great ways to manipulate arrays in JavaScript.

Leave a Reply