I was using Array(n).fill([]) to initialize a dynamic 2d array and using push to insert. It kept inserting into all the sub-arrays. I cannot figure out why this is happening.
Here are the two different codes.
let n=3
let madeWithConstructor = new Array(n).fill([]);
madeWithConstructor[0].push(3);
this will insert value 3 in all sub-arrays.
let n=3
let madeWithLiteral = [];
for(let i=0;i<n;i++){
madeWithLiteral.push([]);
}
madeWithLiteral[0].push(3);
madeWithLiteral;
this gives the desired output i.e. only the sub-array at index 0 = 3