Greetings, fellow coders!
I have recently passed the Chunky Monkey JavaScript challenge (see below).
However, I could not get my code to work until I added the newArr[i] = [];
line (first line in the first for loop). Without it, I got the error “newArr[i] is undefined”.
Why is that? Why can’t I just refer to newArr[i][j]
in the second for loop without it?
function chunkArrayInGroups(arr, size) {
let newArr = [];
let counter = 0;
for (let i = 0; counter < arr.length; i++) {
newArr[i] = [];
for (let j = 0; j < size && counter < arr.length; j++) {
newArr[i][j] = arr[counter];
counter++;
}
}
return newArr;
}