How this code in js is working?

I wrote a simple code in js in which i have initialised 2 arrays and then inside nested loops - in inner loop i am pushing value of i in row array and in outer loop i am pushing that row array in my newarray array.i do realise that after pushing row into newarray any change i make in row array will be reflected in my newarray also, but after second iteration of outer loop i expect my output for “before:newarray” line to be 0,0,1,1,0,0,1,1,2,2,0,0,1,1,2,2 but it is different. can someone please explain why this is happening? link to the code is given below https://playcode.io/332180?tabs=console&script.js&output

You’re declaring row once and then pushing the same reference to it into newArray three times. All three items in newArray point to the same values, so all three will be identical. You need to copy your row values into a new array and push that if you don’t want every row of newArray to be affected by changes to row.

1 Like

In conventional matrix notation m X n matrix signifies a matrix with m rows and n columns, is that your intent ? Right now, you are generating a 3 X 6 matrix while your input looks like it is a 3 X 2, that’s why I’m asking…