I think I’m taking the wrong approach. Wondering if I could get some tips (without solutions). Thank you in advance.
I’m certain there’s an easier way to divide the array into the correct number of groups (subarrays). The following solution satisfies the first three conditions on https://www.freecodecamp.org/challenges/chunky-monkey:
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]].
function chunkArrayInGroups(arr, size) {
var newArray = [];
for (var i = 0; i < Math.floor(arr.length/size); i++) {
newArray[i] = arr.slice(size*i,size*(i+1));
}
return newArray;
}
chunkArrayInGroups();
It doesn’t satisfy the other four conditions:
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]].
In order to do so, I need to change the second parameter in the for loop from i < Math.floor(arr.length/size) to i < (Math.floor(arr.length/size) + 1).
This modified code then does not work for the first three conditions as it inserts an empty array element into the main array.