Chunk Monkey, 2d arrays

I just got no clue how to even start here, I’ve been looking a bit about 2d arrays but it’s kind of confusing, can you guys give some tips?

There’s already a guide for this. Check it out.

I don’t understand why the if condition is using modulus and checking if it’s -1, could you give some explanation?

1 Like

Honestly that part with the modulus doesn’t make sense to me and confused me. I looked up slice() and push() and used those instead:

function chunkArrayInGroups(arr, size) {

  newArray = [];
  iter = 0;
  iter = iter + size;
  return newArray;

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

We start out inside the function by declaring newArray, the array that will hold the other arrays that we will return at the end. I also declare another variable iter, used in the .slice() function.

The iter variable basically keeps track of how far through the array passed via the 1st argument we’ve sliced through. That’s why on the line that intializes the while loop, I’ve declared while(iter<arr.length), because once we’ve passed the arr.length we have no more of the array to slice.

The next line takes a slice out of arr, slicing at slice(iter,iter+size). This ensures we only slice out the size of the chunk that we want at a time, and pushes what we sliced into the newArray. The next line in the loop sets iter equal to iter + size, incrementing the loop by the size that was passed as the 2nd argument to the function.

The function continues to slice out pieces of the arr array, and put those pieces as their own individual arrays inside yet another array we declared newArray.

Yes! This is also the method I ended up using, much simpler

the modulus part seems to be just to find out if the current index is divisible by the total size.
The index begins at 0, the size at 1, that’s why it has to be size -1. If the index is divisible, that means you have the right amount of variables in the array. It could be a +1 % size, too, i guess.

a +1 % size does not work by the way.

Still trying to figure out why does this (a % size !== size - 1) even work though :frowning:

(a + 1) % size !== 0
That’s how it works and I think it is more obvious. Every time index +1 divides by size of array without remainder - it is the time to start new subarray.

(a % size !== size - 1) is too kinky in my opinion.