Hi
, Iām doing 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.ā
function chunkArrayInGroups(arr, size) {
var a = arr;
var b = [];
for ( var i = arr.length; i > 0; i - size) {
b.push(a.splice(-size));
}
return b.pop();
}
I know thereās an infinite loop, I believe it has something to do with (i - size), but I canāt figure it outā¦
If anyone could help, it would be very appreciated, thanks.
Also, when I relocate āreturn b.pop()ā above the curly braces, it sends out half of what i want, but wonāt do the rest?
First of all, be sure to precede and follow your code with three backticks (below the ESC key) so it formats nicely in the forum:
As to your code, yes, that is the cause of your infinite loop. You are never changing i. The statement i - size
doesnāt change i. I think you want:
for ( var i = arr.length; i > 0; i -= size) {
And Iām not sure about:
return b.pop();
Why are you popping? If you return b, you are a step closer.
Thank you, Iāll make sure I backtick in the future. Yea, the pop is from an old version where I was going to have ābā come equipped with a nested array, but I found out I can start an empty one.
Do you know why (i - size) wonāt work? Thanks for the help.
Do you know why (i - size) wonāt work?
Because it doesnāt do anything. That part of the for loop is supposed to tell what to do after each loop, usually changing your index variable. For example, usually you index i with something like i++
. You are trying to subtract from i - thatās fine. But you arenāt changing i with (i - size)
it evaluates a number but doesnāt change i. If you want it to reduce i by size each iteration, then you have to use i-=size
.
It is doneā¦
Thanks again.