Capitalise names - Mutate original array

Viewed 64

I have the following array:

const people = [
    "JoHn", "ChrISTiana", "anThoNY", "MARia", "jaMeS", "MIChaEl", "jeNNIFeR"
];

I want to capitalise the first letter of each word and lowercase the rest.

I have used the following function to generate a new array:

let capitaliseNames = (arr) => {
  return arr.map((item) => item[0].toUpperCase() + item.slice(1).toLowerCase());
};

But how do I mutate the original array? I have tried the same approach but using forEach and it doesn't seem to work.

4 Answers

This will do the work

let capitaliseNames = (arr) => { arr.forEach((elem, i) => { arr[i] = elem[0].toUpperCase() + elem.slice(1).toLowerCase() }); };

First: toLowerCase() then you can use a custom function for the mutation the first letter.

UPDATE Use a loop where you can manipulate the original array. For example a for loop.

const people = ["JoHn", "ChrISTiana", "anThoNY", "MARia", "jaMeS", "MIChaEl", "jeNNIFeR"];

for(let i = 0; i < people.length; i++) {  
   people[i] = capitalizeFirstLetter( people[i].toLowerCase() ) ;
}

function capitalizeFirstLetter(str) {
  return str[0].toUpperCase() + str.slice(1);
}

console.log(people)

Use forEach() instead of map() and reassign the mutated value back to the original array:

const people = ["JoHn", "ChrISTiana", "anThoNY", "MARia",
                "jaMeS", "MIChaEl", "jeNNIFeR"];

const capitaliseNames = (arr) => arr.forEach(
  (v, i, a) => a[i] = v[0].toUpperCase() + v.slice(1).toLowerCase()
);

capitaliseNames(people);

console.log(people);

Had a go using the for loop and this works:

let capitaliseNames = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1).toLowerCase();
    }
}
Related