Chunky Monkey question

Chunky Monkey question
0.0 0

#1

Tell us what’s happening:
Hello. So I came up with the following code to Chunky Monkey. For some reason the last two elements are omitted each time, and also if the last array would not have two elements, it is also omitted. I think it is because the end argument of slice needs to be larger than the length of the array, which would by the end of the for loop be 2, when indexes 4 and 5 are left in forArr. But it is still just equal to the array length. I tried multiple codes but am at a loss. Please tell me what I am missing here.

Your code so far

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var m = arr.join("");
  var newArr = [];
  var forArr = arr;
  var n=0;
  

  for (i=0;i<forArr.length;i++) {
  newArr.push(forArr.slice(0,size));
   
    for (j=0;j<size;j++) {
      forArr.shift();
    } 
   
  }return newArr;
}

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

Your browser information:

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

Link to the challenge:


#2

Work out what the last “chunk” length should be and add this after all the other loops finish.


#3

I took a look and came up with the following code:


function chunkArrayInGroups(arr, size) {
  // Break it up.
  var m = arr.join("");
  var newArr = [];
  var forArr = arr;
  var n=0;
  

  for (i=0;i<forArr.length;i++) {
  newArr.push(forArr.slice(0,size));
   
    for (j=0;j<size;j++) {
      forArr.shift();
    } 
   
  }
  if (forArr.length>0) {
  newArr.push(forArr);
}
  return newArr;
}

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

As you can see, for the last test, it does for some reason ignore the fact that the last sub-array still contains three elements. I tried to add an else to the if statement, and re-add the for loops above but with no result. I can’t tell why this is happening.


#4

The problem is since you are modifying forArr (with shift) as you are iterating over it, you are changing the length each time.

In the first for loop iteration, i = 0 and forArr.length = 9. You slice the first two elements of forArr (0 and 1) and add the result to newArr.

In the second for loop iteration, i = 1 and forArr.length = 7. You slice the first two elements of forArr (2 and 3) and add the result to newArr.

In the third for loop iteration, i = 2 and forArr.length = 5. You slice the first two elements of forArr (4 and 5) and add the result to newArr.

In the fourth for loop iteration, i = 3 and forArr.length = 3. Since your for loop condition checks if i < forArr.length is true, your for loop is exited, because 3 is not less than 3.

After the for loop, you check if forArr.length > 0 and it is (3 > 0), so you push the remaining forArr array into newArr.