0

I would expect the following code to return the result (matrix)

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

but it returns: [ [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0] ]

I cannot see how row is [0,0,0,0,0,0] for each iteration of the outer loop?

I see row iterating from [0,0] to [0,0,0,0] to [0,0,0,0,0,0] and pushing to newArray on each instance. However, this is evidently wrong.

Can anyone explain this result for me?

2
  • 2
    This happens because arrays are reference types in JavaScript (meaning when you do newArray.push(row) you are only pushing a reference to row so when its value changes, it changes everywhere). Commented Oct 17, 2020 at 8:51
  • 1
    Ok, I get it! I can see this being something that you need to watch out for.. by value or by reference knock on effects. I wasn't fully aware that the reference was keep to the variable after pushing into the array, I thought it was new memory space.. but clearly not. Thanks Commented Oct 17, 2020 at 9:11

3 Answers 3

3

You could push a copy of row. This eliminates the same object reference.

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

Sign up to request clarification or add additional context in comments.

Comments

2

The bounds checking was wrong in the inner loop according to your output, in each iteration of the outer loop allocate a new array of i * 2 length.

You can use Array.prototype.fill to simplify your code more.

function zeroArray(m, n) {
  const newArray = [];
  for (let i = 1; i <= m; i++) {
    const row = new Array(i * 2).fill(0);
    newArray.push(row);
  }
  return newArray;
}

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

Comments

0

Your inner loop is run for every value of n, then again for every value of m in the out loop.

For every number in M > Run every number in N and push to row. 3*2 gives 6 results in that table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.