Chunky Monkey (Got it to work by accident so don't really understand one part)

Just arrived at Chunky Monkey (on Basic Algorithm Scripting) and got it to work smoothly with the following code:

[code]function chunkArrayInGroups(arr, size) {
// Break it up.
var slicedArr;
var newArr=[];
for(i=0; i<arr.length; i++){
slicedArr = arr.slice(i, size+i);

return newArr;

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

Although, at first I was stuck because in the “slice” line I was doing:

instead of

And I don’t really understand why you have to put size+i instead of just size since, for example, if size is 2, it’s gonna slice two from where it is starting… or am I seeing this wrong? Probably not really important step but I’m just trying to understand every single of bit of these.

When using Array.slice(), the second argument is the index at which to stop the slice, but does not include that element. So, if made a slice of size size, it would be one element short. Example

[0,1,2,3].slice(0, 2) //returns elements 0 and 1, does NOT include 2

This means if you gave array.slice() size every time, it would always try to end the slice at the same index. What you want is for the slice to change depending on i, which is why your code works.


Damn yes, that makes sense! I was seeing the Array.slice() function wrongly. Thanks dude, totally got it now!

1 Like