0

while practicing with loops I receive kind of weird to me result.

let a = [];
let b = [];

for (let i=0; i<2; i++){
  for (let j=0; j<2;j++){
      a.push(0);

  }
  b.push(a);
  console.log(a);
  console.log(b);
}

Output looks like this:

//values of arrays after first iteration of outside loop
[ 0, 0 ]
[ [ 0, 0 ] ]
//values of arrays after second...
[ 0, 0, 0, 0 ]
[ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]

I wonder why value of array b is not equal to [ [0, 0], [0, 0, 0, 0] ]?

2
  • 1
    You never make a copy of a, so the same array is pushed onto b each time through the outer loop. Commented Dec 5, 2018 at 17:01
  • Try -> b.push([...a]); to get the output you expect. Commented Dec 5, 2018 at 17:16

1 Answer 1

1

Basically you are always using the same a array.

At the start of the second iteration a is [0, 0] and you push 2 extra 0s there.

And b is basically [a, a] in the end, so if you keep feeding a 0s, it's elements will keep growing.

If you want to create a 2D array you would have to make this little modification:

let b = [];

for (let i=0; i<2; i++){
  let a = [];
  for (let j=0; j<2;j++){
      a.push(0);

  }
  b.push(a);
  console.log(a);
  console.log(b);
}

Moving the creation of let a into the outer loop means every time that cycles you will create a new, temporal a to be later pushed to b.

To get the result you want you need to make a copy of the array a, instead, making it:

let a = [];
let b = [];

for (let i=0; i<2; i++){
  for (let j=0; j<2;j++){
      a.push(0);
}
  b.push(a.slice());
  console.log(a);
  console.log(b);
}
Sign up to request clarification or add additional context in comments.

4 Comments

That's not going to give the result the OP is after.
Unless I misunderstood what he wanted, it will. Could you elaborate?
In his question he expected b = [ [0, 0], [0, 0, 0, 0] ] But with this code it's going to be [[0,0],[0,0]] instead,. The OP has accepted your answer so, maybe he does want [[0,0],[0,0]]..
Oh, true, I indeed misunderstood. Gonna edit it right away

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.