Chunky Monkey var incrementation

Tell us what’s happening:
Hello,
I’ve managed to solve the exercise, I just don’t really understand why my code wouldn’t work without introducing the “m” variable, when doing the slice at first I tried chunked.push(arr.slice(i, i+=size)), but that would skip some values after the first iteration, so I introduced the variable m. I would expect i to work the same, so with an array chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7], 2); it would slice the initial array at indexes (0, 2), (2, 4), (4, 6), (6, 8), but in reality it only does (0, 2) and (4,6). Does the value of i increase even inside the slice function? Therefore by doing i+=size in the cycle definition and slice function the variable i is incremented twice?
Thank you,
Tom

Your code so far

function chunkArrayInGroups(arr, size) {
  
  var chunked = [];
  var m = 0;
    for (i = 0; i<arr.length; i+=size) {
     chunked.push(arr.slice(i, m+=size));
    }
  
  return chunked;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7], 2);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0.

Link to the challenge:
https://www.freecodecamp.org/challenges/chunky-monkey

You can do it without the m variable:

function chunkArrayInGroups(arr, size) {
  const chunked = [];
  for (let i = 0; i < arr.length; i += size) {
    chunked.push(arr.slice(i, i + size));
  }
  return chunked;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7], 2);

Note that the second argument to slice must use the + operator rather than +=, otherwise you end up incrementing i twice on each iteration of the loop.

1 Like

In your original code you are incrementing i in both the for loop and the push function.

Edit - Or as above in better detail :slight_smile: