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

147
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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