Heggy Castaneda
Jul 28, 2017 · 2 min read

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.

unction chunkArrayInGroups(arr, size) {
// Break it up.
return arr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);// testcases: 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]].

Review) arr.splice() method arr.splice(position to start delete, how many items to delete). Original array get mutated.

https://repl.it/Jn8Q/6
var arr = ["a", "b", "c", "d"];
// arr.splice(start position, number of items to delete)
arr.splice(0, 2); // output: ["a", "b"] what has been deleted
arr; // output: ["c", "d"] original array has been mutated
https://repl.it/Jn8Q/6
var arr = ["a", "b", "c", "d"];
// try splice more than what is left in the array
arr.splice(0, 5); // only 4 items currently in the array
// output: ["a", "b", "c", "d"] whatever is available in arr

Finally, it is important to have holdingPot outside of While loop. If it were inside, holdingPot get reset each time and our result will only have the last .spliced array alone inside.

https://repl.it/Jn8Q/5
function chunkArr (arr, size) {
var holdingPot = [];

while (arr.length !== 0) {
// since holdingPot is called outside of while stmt
// it will accumulate information
holdingPot.push(arr.splice(0, size));
}
return holdingPot;
}
debugger;
chunkArr(["a", "b", "c", "d"], 2);
Heggy Castaneda

Written by

like to build things

More From Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade