Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

72
Visualizações
Capitalise names - Mutate original array

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This will do the work

let capitaliseNames = (arr) => { arr.forEach((elem, i) => { arr[i] = elem[0].toUpperCase() + elem.slice(1).toLowerCase() }); };
about 4 years ago · Juan Pablo Isaza Relatório

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

0

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);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda