Working on a few beginner algorithmic exercises in JS. I am not understanding how "chunking" works when it gets to the "if" statement.
The main confusion I have is after iterating to the 2nd value; because in the first run, it meets the criteria of last being undefined; so the "1" pushes into the chunked variable. So once the second variable comes in, 2, since last is now defined and the length of Last does not equal to the "len" argument, it'll go to the else part. The 2 will get pushed into "last" and it'll form last = "[1],2"?
Then, when the third value (3), starts coming in, this is when I get even more confused. How does the if statement's chunked.push([number]) know to exactly push [1],2 into chunked when number at that point is also 3? Is it omitting 3?. I know the length of last at that point meets len but how does it formulate from [1],2 to the chunk [1,2]?
I was assuming 3 would also get pushed into "last".
I do apologize if this sounds confusing as well! I looked at many tutorials on solving this same problem online but no where explains it in detail.
function chunkedArr(arr, len){
const chunked = [];
for (let number of arr){
const last = chunked[chunked.length-1]
console.log(last)
if(!last || last.length === len){
chunked.push( [number]);
} else {
last.push(number)
}
}
return chunked;
}
console.log(chunkedArr([1,2,3,4,5,6],2))