Use Caution When Reinitializing Variables Inside a Loop Still getting wrong answer why?

Tell us what’s happening:

Your code so far


function zeroArray(m, n) {
  // Creates a 2-D array with m rows and n columns of zeroes
  let newArray = [];
  let row = [];
  for (let i = 0; i < m; i++) {
    // Adds the m-th row into newArray
    
    for (let j = 0; j < n; j++) {
      // Pushes n zeroes into the current row to create the columns
      row.push(0);
    }
    // Pushes the current row, which now has n zeroes in it, to the array
    newArray.push(0);
  }
  return newArray;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop

Blockquote

This is answer why?

function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
let row = [];
for (let j = 0; j < n; j++) {
// Pushes n zeroes into the current row to create the columns
row.push(0);
}
for (let i = 0; i < m; i++) {
// Adds the m-th row into newArray

// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(row);

}
return newArray;
}

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

1 Like

You need your first ‘for loop’ to push 0’s into the row array ‘n’ number of times, when that ‘for loop’ is done, you need a second for loop to push the new row array into the newArray array ‘m’ number of times. If you put the for loops inside one another, the first ‘for loop’ will push 0 into the row array just one time then move to the second ‘for loop’ and push the array ‘m’ number of times into new array. Then it will go back to the first ‘for loop’ and repeat.

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

zeroArray(3, 2); //output: [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
zeroArray(4, 2); //output: [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]

2 Likes

Awesome explain. I got it now

1 Like

Why don´t we get an array like this instead, before editing the code?

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

Hi,
I found some explanations regarding your question in the post linked below:


Hope it helps.
Regards.

4 Likes

Wanna like this one TWICE!! Great re-use of a past post, and great researching skills. Kudos!

Wow that sounds vain. Not really my point, I just like to see folks using the forums as a searchable archive of incredibly useful content that it’s become.

1 Like

Thank you!
Learning and sharing what I learned/found.

1 Like