Chunky monkey challenge: TypeError:

Chunky monkey challenge: TypeError:
0

#1

My Chunky monkey function works on a size that divides evenly into the array length. However if I a value that does not divide evenly I recive this error in the console: "TypeError: Cannot read property ‘push’ of undefined"
Can some one please help me figure this out?
Here is my code:

function chunkArrayInGroups(arr, size) {
  var nArr =[[],[]];
  var k = 0;
  var nArrRows;
  /**
   *
   * if size divides evenly into the length of arr 
   * then set the number of rows to the dividend of the two
   * else round the dividend up by 1 and set the number of rows to the result.
   */
  
  if (arr.length%size === 0) {
  	nArrRows = arr.length/size;
  } else {

  	nArrRows = Math.ceil(arr.length/size);
  }
  	

  	//nested loop to populate the array
  	for (var i = 0; i < nArrRows; i++) {
  		for (var j = 0; j < size; j++) {
          if(arr[k] !== null){
          
  			nArr[i].push(arr[k]);
           k++;
          }
           //k++;
  		}
      
  	}
  return nArr;
}

#2

Only one line of your function has a push statement, so that means at some time during the function execution, nArr[i] is becoming undefined. How would this happen?

At the start you have initialized nArr to have two subarrays, nArr[0] = [] and nArr[1] = []. However, after that you calculate the number of rows to iterate over (i < nArrRows), and that could end up being more than two rows.

For instance in the sample tests,
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2) will require 3 rows, and nArrRows is calculated as 3.

In your loop then, the first time through, the function pushes values to nArr[0].
The second time through, the function pushes values to nArr[1].
The third and last time through, i = 2, but there is no such thing as nArr[2]. So, nothing can be pushed to it and you get an error.

Hint: don’t initialize the subarrays in nArr til you know how many rows will be required.

Hope this helps.