Chunk Monkey Question (SPOILER)

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];
  return newArr;

because you’re nesting an array inside of an array. You need to explicitly define the array member as a sub-array, or it will assume it’s a primitive/string/function/whatever.

Ah ok, that makes sense. Much like I had to define the first array in the second line?

Many thanks.

1 Like

Exactly like that, yes.

1 Like