Array Chunking?

I am reading an article on algorithm problems. Array chunking is quite a common problem and I can solve it with for or while loop but I don`t understand the following solution:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      function chunk(array, size) {
        const chunks = [];

        for (let item of array) {
          const lastChunk = chunks[chunks.length - 1];
          if (!lastChunk || lastChunk.length === size) chunks.push([item]);
          else lastChunk.push(item);

        return chunks;
      console.log(chunk([1, 2, 3, 4], 2));

Can sb explain it to me pls? :pray:

Is there something in particular you don’t understand?

Well, I understand that this is a function with two parameters. In it defines a variable and then iterates through the array with a for of loop.
Then it defines another variable and it continues with a condition.
I dont understand why lastchunk is equal to chunks[chunks.length - 1]. I mean I dont get the idea of the code.

Just to be clear, that line is setting the value of lastchunk to chunks[chunks.length - 1]. So the first time through the for loop, what is the value of lastchunk going to be set to?

Well, the first time it is undefined, cause chunks is empty. Then after the condition… I think it is 1. Honestly I dont know what !lastChunk means. I dont know what is logical not + undefined, maybe defined.
LastChunk.length cannot be equal to size cause it is empty. So the else branch of condition runs, that is why the result 1.
Then the for of loop runs again with 2.
Am I right? :nerd_face:

Correct. So what will happen? What will the array chunks be after the first iteration? (Assuming we are using chunk([1, 2, 3, 4], 2) as the example).

After the first iteration chunks stays empty.

Show me in the code where this happens. Remember what you said earlier, on the first iteration, lastChunk is set to undefined here:

const lastChunk = chunks[chunks.length - 1];

Following that assignment, you have an if and an else statement. If lastChunk is undefined then which statement is going to be triggered?

So I’ll ask again, after the first iteration, what will the array chunks equal?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.