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

127
Visualizações
2D Array loop behaving strangely (FCC)

I'm doing a learning exercise and am trying to understand the following code. I thought I had a handle on arrays and loops, but this one has got me very confused.

The below code:

  function zeroArray(m, n) 
  {  
  let newArray = [];
  let row = [];

  for (let i = 0; i < m; i++) 
  {    
    for (let j = 0; j < n; j++) 
    {      
      row.push(0);
    }    
    newArray.push(row);
  }
  return newArray;

 }

 let matrix = zeroArray(3, 2);
 console.log(matrix);

Returns

[ [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ] ]

However I would have expected it to return

[ [ 0, 0, ],
  [ 0, 0, 0, 0, ],
  [ 0, 0, 0, 0, 0, 0 ] ]

Given that in each i loop, we are pushing (0) to row[] twice, before pushing row[] into newArray.

This isn't happening though, and in my VSCode debugger it looks as though in each i loop, every existing index of newArray is being updated with the latest version of the row[] array.

Why is this?

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

0

You need to make a copy of the array when pushing to newArray:

function zeroArray(m, n) {
  let newArray = [];
  let row = [];

  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      row.push(0);
    }
    newArray.push(row.slice());
  }
  return newArray;

}

let matrix = zeroArray(3, 2);
console.log(JSON.stringify(matrix));

about 4 years ago · Juan Pablo Isaza Relatório

0

1) Start outer loop with i = 1 upto i <= m, so the loop count will be m

for (let i = 1; i <= m; i++) {

2) You should create a new row every time the inner loop start and push row into newArray after the inner loop ends

3) Set inner loop condition as j < n * i

  for (let j = 0; j < n * i; j++) {

function zeroArray(m, n) {
  let newArray = [];
  // const row = []   // (-)
  for (let i = 1; i <= m; i++) {
    const row = []; // (+)
    for (let j = 0; j < n * i; j++) { // (+)
      row.push(0);
    }
    newArray.push(row);
  }
  return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

Matrix m x n should be m rows and n cols. So for 3, 2 you expect

[
  [0, 0],
  [0, 0],
  [0, 0],
]

Just declare row inside the first loop:

function zeroArray(m, n) {
  const newArray = [];

  for (let i = 0; i < m; i++) {
    const row = [];
    for (let j = 0; j < n; j++) {
      row.push(0);
    }
    newArray.push(row);
  }
  return newArray;

}

let matrix = zeroArray(3, 2);
console.log(matrix);

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