# Chunky monkey (getting empty subarrays pushed in the end of array)

It might be weird way of solving it but I almost done it – the only problem left is that I’m getting empty subarrays pushed in the end (in cases when given as argument array can be divided in groups without remainder.)
I don’t understand how is that possible – part of function than slicing and pushing subarrays is the same for cases for array that give remainder when divided in groups, and it works well there.

function chunkArrayInGroups(arr, size) {
var subarray = arr.slice (0,size);
var newarray = [];
newarray.push(subarray);
//console.log(newarray);
var arrlength = arr.length;
var parts = arrlength/size;
if (parts.isInteger) {
while (newarray.length < parts) {
subarray = arr.slice ((newarray.length*size),       ((newarray.length*size)+size));
newarray.push(subarray);
}
}
else {
var intparts = Math.floor(parts);
while (newarray.length < intparts){
subarray = arr.slice ((newarray.length*size),((newarray.length*size)+size));
newarray.push(subarray);
}
subarray = arr.slice ((newarray.length*size));
newarray.push (subarray);
}
//console.log(newarray);
return newarray;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

Hi,

Your code looks a bit confusing to me. In any case, I had a similar problem but I got empty arrays also in the middle of the solution array.

Anyway, this problem actually is pretty simple. To solve it you could just produce a for loop that scans the array to slice. The real trick in this problem is how to increment the i for loop number after every iteration. As a beginner (i don’t know if you are but i’m still very green) you might think that the i variable should be only increased by one (the tipical i++). but guess by who much you could increment it as well (hint you have this value in you function right at the beginning).

After that, I believe you should know how to solve the problem by fine tuning your slice method values.

I hope I made myself understandable and I’m willing to help more if you have more questions.

1 Like