For loop inconsistency

The console log for this code is [ [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ].
I understand that the row array should be reset in order for the function to have the desired output, but why isn’t the log for this code (as it currently is) the following one: [ [ 0, 0 ], [ 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0 ] ] ?
The way I see it, if the row array is not reset, it should have two more zeros after each outer loop. But that would mean that the number of zeros should be increased in each column. However, the log shows six zeros in each column.

  **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
  //row = []
  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(row);
}
return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36.

Challenge: Use Caution When Reinitializing Variables Inside a Loop

Link to the challenge:

this is pushing a reference to the row array, not a copy
it means that what’s alteady inside newArray changes when a new element is added to row

for a graphic rapresentation you can execute your code with this:
http://pythontutor.com/javascript.html

Thank you very much. I understand what the problem was now. Is there a way to insert the array’s values instead of the array itself, so that the already pushed dimensions don’t change every time the row array is modified?

Thank you very much. I understand what the problem was now. Is there a way to insert the array’s values instead of the array itself, so that the already pushed dimensions don’t change every time the row array is modified?

For a shallow copy, you can use the spread syntax.

I’m looking for a way to have this as the result: [ [ 0, 0 ], [ 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0 ] ]. The spread syntax would do the trick if I do this: newArray.push([…row]), but that would only work for a one dimensional array. Is there a way to do this for a multidimensional arrays (without having to use any kind of loop)?

not easily
or you could do the trick with JSON.stringify and JSON.parse

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.