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

146
Vistas
Updating a sliced array also updates the larger array

I need an explanation for something weird that I noticed with array slicing (NodeJs)

const a = [{ x: 1 }, { x: 3 }, { x: 4 }];
const b = a.slice(0, 2);

for (let input of b) {
  input.y = 1;
}

console.log(b);
console.log(a);

The output has the array a as well as array b updated, even though in the for loop, I am only updating the elements in array b. What am I missing here?

Edit: I tried looking this up as well as went through the MDN Docs for 'slice' but could unfortunately not find anything.

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

0

According to the doc

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end

So basically it creates a new array but the selected elements will still be the same, here are the same references of the objects

You could check it like this by comparing

const a = [{ x: 1 }, { x: 3 }, { x: 4 }];
const b = a.slice(0, 2);

console.log(a[0] === b[0])
console.log(a[1] === b[1])

about 4 years ago · Juan Pablo Isaza Denunciar

0

Array.slice creates a copy of the array, so a !== b, but since a is made out of objects, b still retains the references to those identical objects. So any change you make to the objects in one array, also affects the other array.

You have to deep copy a if you want b to contain entirely new objects.

about 4 years ago · Juan Pablo Isaza Denunciar

0

when you use slice you will get a new array but the objects are same that are in a. If you want to add properties without affecting object on a then you should clone the objects.

Remember: Below code snippet will work if there is no nested objects

const a = [{ x: 1 }, { x: 3 }, { x: 4 }];
const temp = a.slice(0, 2);
const b = [];

for (let obj of temp) {
  const o = { ...obj };
  o.y = 1;
  b.push(o);
}

console.log(a);
console.log(b);

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