# My solution to Chunky Monkey

My solution to Chunky Monkey
0

#1

After trying for a while, I’ve come up with this solution to this challenge. I used both push() and splice(), and a for loop:

``````function chunkArrayInGroups(arr, size) {
// Break it up.
var newArr = [];

//get the total array items
var totalArrayLength = arr.length;

for ( var i = 0; i < totalArrayLength; i++ ) {

//build a new array with the spliced array
newArr.push( arr.splice( 0, size ) );

//check if there are any extra empty arrays
//if there are, delete them
if ( newArr[i].length <= 0 ) {
delete newArr[i];
}

}

return newArr;
}
``````

After it’s been solved it looks very basic, but it really wasn’t.

#2

Nice job! If you put that `if` clause around the `newArr.push()` so it doesn’t add any empty arrays in the first place, you could save a few cycles.

#3

Great suggestion, cheers!

#5

this is my solution…

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

var result = [];

var numberOfGroups = Math.ceil(arr.length / size);

for (i=0; i <numberOfGroups; i++) {

result.push(arr.slice(size * i, size + i * size));

}

return result;

}``````

#6

Spent a whole day trying to figure this out on my own. Was gonna repeat the same thing today then I thought i’d swallow some pride and hit google up

Nice Solution.

#7

All,

Here’s my solution… I created new variables as placeholders (1 for the slice and 1 for the push). I probably could of combined the slice and push in one statement but broke it up.

Anyone else find this problem oddly challenging? Maybe it was just me

``````function chunkArrayInGroups(arr, size) {
var sliceArr = [];
var pushArr = [];

for (var i = 0; i < arr.length; i += size) {
sliceArr = arr.slice(i, i + size);
pushArr.push(sliceArr);
}

return pushArr;

}

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

#8

I remember when I first did this challenge and it seemed like the first challenge where I really had to write out my algorithm in words/steps before attempting to write the code.

FYI, you can simply your solution down to what is shown below. This version does not require the variable named sliceArr and combine the slice and push (as you stated was a possibility). Also, I moved the pushArr declaraction to the for loop.

``````function chunkArrayInGroups(arr, size) {
for (var pushArr = [], i = 0; i < arr.length; i += size) {
pushArr.push(arr.slice(i, i + size));
}
return pushArr;
}
``````

#9

How …“ugh” and “horray” was i when after hours of trying to come up with…aaanything… figuring out this could be a solution.

``````function chunkArrayInGroups(arr, size){
let arrNew = [];
while (arr.length > 0) {
arrNew.push(arr.splice(0, size));
}
return arrNew;
}
``````

#10

#11