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

129
Visualizações
One line Array iterator javascript

I am coming from Python and I am looking for a single line iterator function for any array, where I can also check a condition and return a simple change to the items.

Expected result should match the method:

function arrayEvenItemIncrement(myArray){
    for (let i = 0; i < myArray.length; i++){
        if (myArray[i]%2==0){
            myArray[i]++;
        }
    }
    return myArray;
}

I tried using for (i of myArray){ } but this still doesn't serve my purpose.

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

0

I think the clearest way to do what you want here would be to map to a new array instead of mutating the old one:

const arrayEvenItemIncrement = myArray =>
  myArray.map((val, i) => i % 2 === 1 ? val : val + 1);

If you have to mutate the existing array, it gets significantly uglier.

const arrayEvenItemIncrement = myArray => (
  myArray.forEach((val, i) => { if (i % 2 === 0) myArray[i]++; }), myArray);

or

const arrayEvenItemIncrement = myArray => {
  myArray.forEach((val, i) => { if (i % 2 === 0) myArray[i]++; }); return myArray };

But I wouldn't recommend that - put it on multiple lines instead.

You can technically squeeze any JS code into a single line, but past simple manipulations, it usually isn't a good idea because it sacrifices readability, which is far more important than reducing LoC. Professional, maintainable code is not a golfing competition.

about 4 years ago · Juan Pablo Isaza Relatório

0

Thank you for the answers. I have settled for this:

myArray.forEach(el=>el%2===0?newArray.push(el):null);

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