2

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.

2
  • 2
    Here n[i][j] = arr[index] tries to get the element with index i and then assign the element of the inner array with the arr element. The problem is that your n array has only one element and hence n[i] is undefined where variable i is greater than 0 Commented Apr 16, 2022 at 2:56
  • 1
    @Tanay thanks! I tried creating new Array to push some numbers ,then push Array to n . Now I can get the right two-dimensional array N. My code got ACCEPT! thanks you again! Have a nice day! Commented Apr 16, 2022 at 3:19

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

Comments

0

As the comments showed, it is possible to use .push. This is how I implemented that solution in my case.

const myArray = [[]];
const height = 7;
const width = 8;

for (let i= 0; i < height; i++) {

    if (i> 0) myArray.push([]); // this initialises the array.
    for (let j = 0; j < width; j++) {
        myArray[i][j] = "x";
    }

}

console.log(myArray)

Here is a codepen

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.