My solution to Chunky Monkey

After trying for a while, I’ve come up with this solution to this challenge. I used both push() and splice(), and a for loop:

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr = [];
  
  //get the total array items
  var totalArrayLength = arr.length;
  
  for ( var i = 0; i < totalArrayLength; i++ ) {
   
    //build a new array with the spliced array 
    newArr.push( arr.splice( 0, size ) );
    
    //check if there are any extra empty arrays
    //if there are, delete them
    if ( newArr[i].length <= 0 ) {
      delete newArr[i];
    }
    
  }
  
  return newArr;
}

After it’s been solved it looks very basic, but it really wasn’t.

1 Like

Nice job! If you put that if clause around the newArr.push() so it doesn’t add any empty arrays in the first place, you could save a few cycles.

Great suggestion, cheers!

this is my solution… :flushed:

function chunkArrayInGroups(arr, size) {
  
  
  var result = [];
  
  var numberOfGroups = Math.ceil(arr.length / size);
  
  
 
  
   
  
  
  for (i=0; i <numberOfGroups; i++) {
    
    result.push(arr.slice(size * i, size + i * size));
    
  }
  
  
  return result;

}
1 Like

Spent a whole day trying to figure this out on my own. Was gonna repeat the same thing today then I thought i’d swallow some pride and hit google up :sweat_smile:

Nice Solution.

All,

Here’s my solution… I created new variables as placeholders (1 for the slice and 1 for the push). I probably could of combined the slice and push in one statement but broke it up.

Anyone else find this problem oddly challenging? Maybe it was just me :slight_smile:

function chunkArrayInGroups(arr, size) {
  var sliceArr = [];
  var pushArr = [];

  for (var i = 0; i < arr.length; i += size) {
    sliceArr = arr.slice(i, i + size);
    pushArr.push(sliceArr);
  }

  return pushArr;

}

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

How …“ugh” and “horray” was i when after hours of trying to come up with…aaanything… figuring out this could be a solution.

function chunkArrayInGroups(arr, size){
  let arrNew = [];
  while (arr.length > 0) {
    arrNew.push(arr.splice(0, size));
  }
  return arrNew;
}