Search code examples
javascriptarraysconstantschunking

Chunking Algorithm Help JS


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))


Solution

  • One key insight could be that chunked is an array of arrays.

    In the example, at the second iteration, chunked will not be [1], but [[1]]. Notice that it is an array of an array. So then last gets assigned the only sub-array inside chunked, i.e. [1], and in the else block, value 2 gets appended to that sub-array, so it becomes [1, 2]. Because last really is the sub-array that sits inside chunked, chunked now looks like this: [[1, 2]].

    In the next iteration, the value is 3, and the if condition is true because now last is [1, 2], and thus having the required length 2. At this point the value of last is left untouched. This sub-array is now "full". A new subarray is appended to chunked, so that it looks like [[1, 2], [3]]

    At the next iteration, the value is 4, and now last will be assigned the newer sub-array, i.e. [3]. And so it continues...