Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda