Odd March Bits 8 Bits

Hello. I was doing this kata in codewars Training on Odd March Bits 8 bits | Codewars
and i don’t understand why i can’t get the desired output. This is my code:

function bitMarch (n) {
  let arr = [0,0,0,0,0,0,0,0];
  let aux = n;
  
  while(n>=1) {
    arr.shift();
    arr.push(1);
    n--;
  } 
 let container = [];

  for(let i = 0; i< arr.length - aux + 1; i++) {
      console.log(arr) // this console.log shows me what i want to push,
// i push it but the end result in the container it's allways the same static arr
    	container.push(arr)
    	arr.reverse();
    // console.log(container) but this .log doesn't showme the same
    if(arr[arr.length-1]== 0) {
    	if(arr[i]==1) {
        arr[i+aux]= 1;
        arr[i]= 0;
       arr.reverse() 
      }
    }
  }
	 return container
}

bitMarch(1);

In the console.log inse the for loop arr it’s showed like this:

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

but in the container that i pushed that arr (or i guess i push that arr) return this:


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

If someone can help me i will be very grateful. Thanks!

It’s the same array. Array contains references to actual objects, every time arr is pushed into container there’s another reference of the same array added to container. They all point to single array, which is then mutated. In the end it may appear as multiple arrays are changed at the same time, but in fact there’s only one arr array.

If wrapping mind around this is still hard, you may try looking at how that code is executed, in a tool like: JavaScript Tutor - Visualize JavaScript code execution to learn JavaScript online

1 Like

Nice man, you really helped me a lot, that JS tutor is awesome. I finally get my desired result spreading the arr in a new variable and then pushing that variable.

1 Like