0
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(2, 2);
console.log(matrix)

The first row (after first for loop) is [[0,0]] but next time its [[0,0,0,0], [0,0,0,0]]. And I have no idea why the first row changed. Could you explain? I know that I could reset "row" after newArray.push(row) but then the result would be [[0,0], [0,0]] but I want this result: [[0,0], [0,0,0,0]].

David
  • 1
  • 1
  • You never reset your `row` to empty array. Maybe you need to move it inside first `for`? – Justinas May 28 '21 at 09:23
  • But if I reset it, the result would be [[0,0], [0,0]]. And I want the result to be [[0,0], [0,0,0,0]] – David May 28 '21 at 09:26

2 Answers2

2

The row is the same array when you push to newArray. Create a copy and push will solve the problem.

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(2, 2);
console.log(matrix)
HW Siew
  • 973
  • 8
  • 16
-1

Move the row declaration into the first for loop, so it resets between the first and the second row.

Samuel
  • 49
  • 1
  • 6