''TypeError: Cannot set properties of undefined (setting '0')'----Array assignment

When I was solving a problem on Leetcode, I've defined an empty array. I tried push some numbers then I got this Error. I don't know why. My code here.

        // r and c are already defined numbers,arr is already defined array.
        let n = [[]]
        let index = 0
        for (let i = 0; i < r; i++) {
            for (let j = 0; j < c; j++) {
                    n[i][j] = arr[index]
                    index++;
            }
        }
        return n; 

Leetcode told me n[i][j] = arr[index] had error;

Anyone knows why? thanks.



Solution 1:[1]

Whenever the value of i becomes 1, inside the inner loop it is setting the value to n[i][j], which is n[1][0], here n[1] is undefined and it is accessing the 0th index value of undefined, that is the reason of the error.

the first iteration works fine because there is already an empty array in the 0th index (when i = 0).

here you can try doing this

let n = []
let index = 0
for (let i = 0; i < r; i++) {
    n[i] = [];
    for (let j = 0; j < c; j++) {
        n[i][j] = arr[index];
        index++;
    }
}

return n;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akhil M L