What is wrong with my code
function chunkArrayInGroups(arr, size) {
// Break it up.
let arra = [];
var iz = size;
for (var i = 0; i < arr.length; i+=iz) {
arra.push(arr.slice(i, iz));
iz += size;
}
return arra;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4);
What are you trying to do?
Is this an FCC challenge? if so click the ‘ask for help’ button and that creates a thread that auto-populates a bunch of relevant information.
1 Like
iz += size;, and using iz as the value you add to i in the loop. Because you’re using it to add to i in the loop, i increases very fast and the loop stops quickly, to soon to get the last values. In your example:
-
i is 0. Loop stops when i < 9. Push [0, 1, 2, 3]. Add 4 to i
-
i is 4. Loop stops when i < 9. Push [4, 5, 6, 7] Add 8 to i
-
i is 12. Loop terminates. It should have pushed the final value into a final array ([8]), but it doesn’t do that.
You don’t need iz, you already have size - the loop should increase by i += size,and the slice should take from i to i plus whatever the size is.
1 Like