Th1
Th1

Reputation: 291

How to capitalize the first letter of each word in an array using Array.map() with an arrow function?

How to capitalize the first letter of each word in an array using Array.map() with an arrow function?

What I've tried so far:

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
days.map(day => day.charAt(0).toUpperCase() + day.substr(1));
console.log(day);

Upvotes: 0

Views: 2992

Answers (3)

AndrewL64
AndrewL64

Reputation: 16311

The map() method does not mutate the values in the current array days but creates a new array with the results of calling a provided function on every element in the calling array.

In other words, the map() method does not make any changes to the array you're mapping but what it does is create a new array with the changes made.

So in order to access the new array that you got from map(), you need to assign the mapped array to a new variable say, newDays like this:

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
    
const newDays = days.map(day => day.charAt(0).toUpperCase() + day.substr(1).toLowerCase());
    
console.log(newDays);

Upvotes: 1

quirimmo
quirimmo

Reputation: 9988

Your code works fine. You have just two issues:

1) map returns a new array, it doesn't change the array

2) you are doing console.log(day)

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
console.log(days.map(day => day.charAt(0).toUpperCase() + day.substr(1)));

Upvotes: 0

Raed Khalaf
Raed Khalaf

Reputation: 2065

You can simply use map :

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
const capitalDays = days.map( day => day.charAt(0).toUpperCase() + day. substr(1));

Or use forEach method

days.forEach((day, index) => {
   days[index] = day.charAt(0).toUpperCase() + day.substr(1).toLowerCase();
});

Upvotes: 0

Related Questions