Chunky Monkey(0)

Tell us what’s happening:
I’m making a function that splits an array into chunks of whatever number is put into the size parameter. My code doesn’t seem to be working, though the logic looks to me like it should work. It keeps saying that there is a type error and that it can’t set a property ‘0’ of undefined.

Your code so far

function chunkArrayInGroups(arr, size)
{
  // Break it up.
  var newArr;
  var count = 0;
  var i = 0;
  var grouping = arr.length/(arr.length/size); //For example, an array of 6 in groups of 2 is an array of 6 in groups of 6/(6/2) or 6/(3) = 2
  
  while(i < grouping) 
  {
    for(var j = 0; j < arr.length; j++)
      {
        newArr[i][count] = arr[j];
        count++;
        
        if(count === grouping)
          {
            i++;
            count = 0;
          }
      }
  }
  return newArr;
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.

Link to the challenge:

newArr is left undeclared. Try setting var newArr = []. After that you’ll have the same problem when you try to access newArr[i][count], because newArr[i] is also undefined.

Try setting newArr[i] to an empty array too, but don’t forget to check if it already exists (because otherwise you might overwrite existing data).

for (var j = 0; ...) {
  if (!newArr[i]) {
    newArr[i] = [];
  }
}

You’ll still have failing tests after this though.

Also, it’s a good idea to use Math.floor when dealing with dividing discrete quantities (like array lengths). But when you think about it, the division is redundant, because size already takes the role that grouping does (and the division simplifies to just size anyway).

This is what I have now.


function chunkArrayInGroups(arr, size)
{
  // Break it up.
  var newArr = [[],[]];
  var count = 0;
  var i = 0;
  
  while(i < size) 
  {
    for(var j = 0; j < arr.length; j++)
      {
        newArr[i][count] = arr[j];
        count++;
        
        if(count === size)
          {
            i++;
            count = 0;
          }
      }
  }
  return newArr;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3);

It worked for chunkArrayInGroups([“a”, “b”, “c”, “d”], 2). I have no idea what’s wrong here.

Okay, so from this I see that I need to create an array capable of holding more than two other arrays. How do I do this?