Chunky monkey challenge confusion

Hello everyone! I just finished the “chunky monkey” challenge and I wanted to understand better my solution. I was basically experimenting and arrived at this solution but I really don’t understand why my slice works. I put i there by accident and when I tested it worked. I feel that my slice should not work but it does so if anyone can help explain I would appreciate it.


function chunkArrayInGroups(arr, size) {
let rarr = [];
for (let i = 0; i < arr.length; i+=size) {
let chunk = arr.slice(i, size + i);
rarr.push(chunk);

}
return rarr;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);
  **Your browser information:**

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

Challenge: Chunky Monkey

Link to the challenge:

Any help is appreciated!

Best,
Cy499_Studios

Hi!

To solve this problem,there are a few things you should focus on. The first is the value of “i” with each iteration, the value “i” is set to after each iteration and the arguments passed to the slice method.

When the loop first starts, the value of i is 0 and you are slicing the input array from

 i to size + 1

which turn the arguments passed to the slice method to be

arr.slice(0, 2)

which evaluate to 0 to 2 and the array which would be pushed to the rarr variable is

 ["a", "b"]

which make the value output value to be

[["a", "b"]]

In the next iteration, ,the value of i is set to i +=size which evaluates to 2 and the slice method’s parameters are i and i + size which evaluate to

arr.slice(2, 4)

because of which the array that is next pushed to the array is [“c”, “d”]
now the resulting array is

[["a", "b"], ["c", "d"]] 

Hope this helped! :slight_smile:

1 Like

@staranbeer

Holy smokes, it’s amazing what some perspective can do when your solving a problem. Thank you so much for explaining this to me :smiley:

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