# Chunky Monkey reduce method

Hi there,

I passed the Chunky Monkey challenge with this code (I have commented the parts at the end of lines 3 & 4 that were correct but I don’t fully understand how they work):

``````function chunkArrayInGroups(arr, size) {

var newArray = [];

for (var i = 0; i < arr.length; i = i+size) {       //  i = i+ size
newArray.push(arr.slice(i, i + size));          //  i, i + size
}
return newArray;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
``````

My aim had been to try and solve it as a for loop and then ‘upgrade’ it to use reduce method. I’m just finding it SO hard to understand!

I’ve been reading and reading about reduce and trying to see how it relates to this particular challenge but to be honest I feel pretty lucky to even have passed it with a for loop let alone .reduce.

Any advice that could be given as to exactly how my for loop will translate to .reduce I’d be very grateful

Thanks

I’m not sure how to translate the for-loop to `.reduce`, since each iteration of the loop takes in chunks of items from the array rather than one at a time. It might be possible to use `.reduce`, but I imagine it’ll look messier than using a for-loop.

@kevcomedia

``````function chunkArrayInGroups(arr, size) {
return arr.reduce((groupsArr, _, i) => {
if (!(i % size)) groupsArr.push(arr.slice(i, i + size));
return groupsArr;
},[]);
}
``````

OR a leaner version:

``````const chunkArrayInGroups = (arr, size) => arr.reduce((groupsArr,_,i) => !(i % size)
? (groupsArr.push(arr.slice(i,i+size)), groupsArr)
: groupsArr,[]);
``````
1 Like

Nice. I’ve forgotten that you can also use the index in `.reduce`

Hi there,

Thanks for taking time to reply! Always much appreciated

Hi there,

Thanks for these examples! Really helpful