Chunky Monkey-my solution

Chunky Monkey-my solution
0.0 0

#1

Here is my solution to the Chunky monkey problem.

function chunkArrayInGroups(arr, size) {

var twoDArray=[];
var arrayLength=arr.length;
//this variable calculates number of groupings less the
//left over that will end up in 2D array.
var numOfGroupings=Math.floor(arrayLength/size);
//size of left over end of array
var remainder=arrayLength%size;

//if there is a left over remainder at the end of the array
if(remainder > 0){
twoDArray.unshift(arr.splice(-remainder,remainder));
}

for(var i=0;i<numOfGroupings;i++){
twoDArray.unshift(arr.splice(-size,size));
}
return twoDArray;
}

This code works but I am interested in how to eliminate the need for dealing with the left over
end of the array. This way the program would be simplified to a for loop with one command. Any help/ideas would be appreciated. Thank you.


#2

What I did was first determine how many total groups I need.
The FCC lessons introduced the Math.floor() function that rounds down to the nearest whole number.
Common sense would dictate that hopefully the developers created an equivalent function that rounds up.
So I searched for Javascript Math Object functions
And found: Math.ceil().

Once I have the total # of groups needed, then I implemented a nested for loop. First looping through the total number of groups to create, and then looping through each group creating the arrays with the passed parameter number of items in each array.

Instead of using the hinted push() function, I used shift() instead to build the arrays from the beginning. The 2nd nested loop will end when the last element of the original array has been removed.

Note that nested for loops are perhaps not ideal best practice for performance. But that was just the easiest way for me to get through the exercise.

function chunkArrayInGroups(arr, size) {
  var result = [];
  var groups = Math.ceil(arr.length/size);
  
  for (var g=0; g<groups; g++) {
    var tArr = [];
    
  	for (var i=0; i<size; i++) {
      if (arr.length > 0) {
	      tArr[i] = arr.shift();
      }
  	}
    result[g] = tArr;
  }
  return result;
}

Also, if it’s not quite clear, the nested loop builds the internal array elements based on the size and once that’s built, then it gets added to the final array as a single item.