I just completed this challenge:
In this challenge the objective is to “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 was my initial idea for the code to solve the problem:
function chunkArrayInGroups(arr, size) {
let newArray = [];
let tempArray = [];
for (let i = 0; i < arr.length; i += size) {
tempArray = arr.slice(i, size);
newArray.push(tempArray);
}
return newArray
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
However I could only ever get it to push the first two elements (“a”, “b”) in the arr to newArray. A second array would seemingly be made, but it would be left empty.
I then cheated a bit and looked at the solution in the hints section, and I saw that I only really needed to change this line of code:
tempArray = arr.slice(i, size);
to this:
tempArray = arr.slice(i, i + size);
It works now, but I don’t understand why. And I don’t understand why my initial code was insufficient. Initially i + size should be equal to 2 (i = 0 + 2). But on the second iteration of the loop i should be equal to 2 and i + size would therefore be 2 + 2 which is 4, which, if the array was longer would end up slicing too many elements from it, right?
Anyway, I’m confused. Please help