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

132
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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