What's wrong with this code?
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = []; // or arr = [[]];
for (let i = 0; i < matrix1.length; i++) {
for (let j = 0; j < matrix1[i].length; j++) {
arr[i][j] = matrix1[i][j];
}
}
console.log(arr);
Error is:
Cannot set property '0' of undefined This is when I try to assign the value of an element of
matrix1to the new array.for loopworks for the single dimensional array.
[]is an empty array.[ [] ]is an array with one element which is another array. If you want to clonematrix1you have to addmatrix1.lengtharrays inarrlet arr = [[], [], []];and it worked. Now is there any way we can put number of arrays in main array on the fly? I mean if we have different inputmatrix1with different lengths, can we put those many empty arrays inside the main array? Edit: I read your answer after posting mine and got the idea. Thank you.