Chunky Monkey - My brain is not working

Tell us what’s happening:

Your code so far


  function chunkArrayInGroups(arr, size) {

      var temp = [];
      var result = [];

      for (var a = 0; a < arr.length; a++) {
        if (a % size !== size - 1)
          temp.push(arr[a]);
        else {
          temp.push(arr[a]);
          result.push(temp);
          temp=[];
        }
      }

      if (temp.length !== 0)
        result.push(temp);
      return result;
    }

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey

Could someone help explain what is happening in a few different parts of this code to me? I’m not able to understand it. I don’t know if my math or logic skills just suck.

Why do we need a temporary array and temporary result? Is the Temp to temporarily store parts of the sliced data from the array?

if (a % size !== size - 1) | I’m not understanding what this code means or what it does.

Why are we pushing the loop to temp only to set it back to empty after pushing it to result? What is the point?

temp.push(arr[a]);
result.push(temp);
temp=[];

Isn’t temp empty now? so what is it checking for in terms of the length?

if (temp.length !== 0)

Thank you

The final return value of the function is an array of arrays. result is the final array containing sub arrays (the temp arrays created inside the for loop).

The above checks if the remainder of current index value being iterated over in arr divided by size is not equal to size - `. The point of this check to confirm the current temp size is not filled to capacity. Once the two values are equal it is time to push the current temp array to result and reset temp to an empty array.

Hopefully my explanation of your first question answers this.

Because it is possible that the number of elements in arr is not evenly divisible by size, so there would be extra elements still in temp, so you do one last push to result when that is the case. An example is the following:

chunkArrayInGroups(["a", "b", "c", "d", "e"], 2);

The for loop would finish and result would look like:

[ [ 'a', 'b' ], [ 'c', 'd' ] ]

However, since temp would still have [ 'e' ] in it (temp.length !== 0), you would still need to push it to result.

1 Like

Thank you for the explanation :slight_smile: