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

88
Vistas
Creating new array with updating array element without mutating the original array

This is the array and I want to replace the elements "A" and "B" with "D". I don't want to mutate the original array , So I have used spread operator. But still my original array getting mutating whenever I will update the newArr. I want originalArray should be [["A", 2],["B",1]] and newArr should be [["D", 2],["D",1]] Can anyone suggest me the solution for this

let originalArray = [["A", 2],["B",1]];
 let newArr = [ ...originalArray  ];
    for(let i=0;i<newArr.length;i++){
     newArr[i][0] = "D";
    }
    console.log(originalArray )
    console.log(newArr)

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

0

Spreading does not imply a deep copy. You have a two dimensional array so when you spread the top level, the nested arrays are still referencing the original array:

let originalArray = [["A", 2], ["B",1]];
let newArr = [...originalArray];

console.log(originalArray[0] === newArr[0]) // true

the simplest change necessary is to also spread the nested array

let originalArray = [["A", 2], ["B",1]];
let newArr = [...originalArray];
for(let i = 0; i < newArr.length; i++) {
    newArr[i] = ["D", ...newArr[i].slice(1)]; // make a copy here as well using slice and omitting the first element
}
console.log(originalArray )
console.log(newArr)
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