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

94
Visualizações
Pushing an array to another array

I'm new to javascript and I've been going through some exercises but I can't figure out why this code works like this,

    let newArray = [];
    let arr1 = [];
    for (let i = 0; i < 2; i++) {

      for (let j = 0; j < 2; j++) {

        arr1.push(0);
        //console.log('Arr1:',arr1); 
      }

      newArray.push(arr1);
      //console.log('New Array:', newArray)
      
    }
    console.log(newArray);
  

According to me, this block of code should output [[0,0][0,0,0,0]] but the real output is [[0,0,0,0][0,0,0,0]].

I tried console logging after every iteration(by removing the comments) and I can't seem to find where it goes wrong. It seems like it all goes well until the last log. I'd appreciate your help.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

One way to do it is to avoid using push() function and use concat() function instead. More about it on existing discussion.

You would have something like:

newArray = newArray.concat(arr)
about 4 years ago · Juan Pablo Isaza Relatório

0

You should use Array#slice or spread syntax to copy the array instead of pushing the same reference multiple times, since subsequent changes will continue to be reflected.

let newArray = [];
let arr1 = [];
for (let i = 0; i < 2; i++) {
  for (let j = 0; j < 2; j++) {
    arr1.push(0);
  }
  newArray.push(arr1.slice());
}
console.log(JSON.stringify(newArray));

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