Doing a freeCodeCamp challenge called "Chunky Monkey". The objective is to create a function that takes two parameters: a 1D array and a number for size.
The array is to be split into a number of groups of the length size (up to that number), thus creating a 2D array.
In my first attempt, my code was:
function chunkArrayInGroups(arr, size) {
var set = arr.length / size;
var count = 0;
set = Math.ceil(set); //ensure that an integer is obtained
var array = [];
for (var i = 0; i < set; i++) {
array[i] = []; //ensure each element i is an array
for (var j = 0; j < size; j++) {
array[i][j] = arr[count]; //obtain values from passed array, arr
count++;
}
}
return array;
}
var result = chunkArrayInGroups(["a", "b", "c", "d"], 2);
console.log(result);
I have traced this code a few times, but I cannot tell why it is wrong. Can someone please spot the error in it?
I eventually tackled the problem using a slightly different method, and it worked, but I am very interested in why the code above did not work.
chunkArrayInGroups(["a", "b", "c", "d"], 2), you get[["a", "b", "c" ],["d", undefined,undefined]]chunkArrayInGroups(["a", "b", "c", "d", "e"], 2);, what is the expected result?[["a", "b"],["c", "d"],["e", undefined]]or[["a", "b"],["c", "d"],["e"]]?chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)should return[[0, 1, 2, 3], [4, 5, 6, 7], [8]].