Chunky Monkey : Why doesnt this work

This code works as far as getting even number of sub arrays, like [2,3],[5,7] in [2,3,5,7],2
but it doesnt do the remaining elements if there are some left over as in [2,3,5,7,6],3 so the left over ones would be [7,6]. This should be taken care of by the code that follows the ending bracket of the first for loop, but somehow it doesnt work. Am I missing something on the scope level for the arrCtr value? Doesnt let when used outside any loops create a global variable?

Your code so far


function chunkArrayInGroups(arr, size) {
  let len=arr.length;
  let divArr=[];
  let newArr=[];
  let numDiv=len/size;
  var arrCtr=0;
  let remainElements=len%size;
  for (let divNum=0; divNum<numDiv; divNum++)
  {
    divArr=[];
    for (let element=0; element< size; element++)
    {
      divArr.push(arr[arrCtr++]);
    }
    newArr.push(divArr);
  }
  divArr=[];
  if (remainElements>0)
  {
    for (let i=0; i<remainElements; i++)
    {
      divArr.push(arr[arrCtr++]);
    }
    newArr.push(divArr);
  }
  return newArr;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey

For the call chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), your function returns the following array:

[ [ 0, 1, 2, 3 ], [ 4, 5, undefined, undefined ], [ undefined, undefined ] ]

instead of:

 [[0, 1, 2, 3], [4, 5]]

Before your function even gets to the following code, newArr is [ [ 0, 1, 2, 3 ], [ 4, 5, undefined, undefined ] ]. The only thing wrong with the array is that it contains to extra elements (with values of undefined) in the 2nd sub array. You definitely should not be pushing anything else after this part.

  divArr = [];
  if (remainElements > 0) {
    for (let i = 0; i < remainElements; i++) {
      divArr.push(arr[arrCtr++]);
    }
    newArr.push(divArr);
  }
1 Like

Ha ha ha ha. Now I see what they say when they say it is harder for someone who knows a language to learn another language. Im used to programming in java and default integer division, and I overlooked the fact that I get floating division by default in javascript. All I had to do was change the

let numDiv=len/size;

to

let numDiv=Math.floor(len/size);