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

150
Vistas
Why is map changing my original array while iterating over?
const z = [
    [
        "Almond",
        54
    ],
    [
        "Oats",
        75
    ],
    [
        "Raisins",
        undefined
    ]
]
let temp=[];
z.map((item, index) => {
    temp.push(item);
    if (item[item.length - 1] === undefined) {
      temp[index][1] = 'Not available'
    }
  });
console.log(temp)
console.log(z);

I'm changing the undefined entry to 'Not available' by creating another array. I'm not able to understand my z array is changing along with temp.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

A better approach would be to return a result array, mapping each entry in the item array to 'Not available' if it is undefined and then last entry in the item array.

This will leave the original z array untouched.

const z = [ [ "Almond", 54 ], [ "Oats", 75 ], [ "Raisins", undefined ] ]

let result = z.map((item, index) => {
    return item.map((val, idx) =>  {
        let notAvailable = (val === undefined) && (idx === item.length -1);
        return notAvailable ? 'Not available': val;
    })
})

console.log('z:', z);
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

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