freeCodeCamp: Chunky Monkey

Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.

Here are some helpful links:

Starting Code:

function chunkArrayInGroups(arr, size) {
// Break it up.
return arr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

Use Cases:

chunkArrayInGroups(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3) should return [[0, 1, 2], [3, 4, 5]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2) should return [[0, 1], [2, 3], [4, 5]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4) should return [[0, 1, 2, 3], [4, 5]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3) should return [[0, 1, 2], [3, 4, 5], [6]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4) should return [[0, 1, 2, 3], [4, 5, 6, 7], [8]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2) should return [[0, 1], [2, 3], [4, 5], [6, 7], [8]].

Solution:

The first solution uses splice() … which I personally find easier to use. But it does destroy the original array that it is called on. The solution shows while (arr.length > 0) {} … you can actually shorten this to while(arr.length){} since it will return false when arr.length is less than or equal to zero.

function chunkArrayInGroups(arr, size) {
// Break it up.
var group = [];
   while (arr.length > 0) {
group.push(arr.splice(0, size));
}
return group;
}

The helpful links in the instructions show using slice(). I find that a little more convoluted, but here is a solution using slice() if you want to go that route. The difference is that we increment a pointer (position) with size to determine what to push onto the group array. As long as that pointer is less than arr.length, we’ll continue to loop and push onto the group array.

function chunkArrayInGroups(arr, size) {
// Break it up.
var group = [];
var position = 0;

while(position < arr.length) {
group.push(arr.slice(position, position+=size));
}
return group;
}