[Help] Chunky Monkey Challenge

I am working on Basic Algorithm Scripting in Front End Development Certification. Really need someone knowledgable explain to me what’s wrong with my code. (Complete newbie please tolerate). Thank you so much!

The Challenge:

Chunky Monkey
Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.

Remember to use Read-Search-Ask if you get stuck. Write your own code.

Here are some helpful links:

Array.prototype.push()
Array.prototype.slice()

My code:

 function chunkArrayInGroups(arr, size) {
 for (var i =0; i < arr.length; i++){
   var final =[];
   var arrthis = arr.slice(size*i, (size*(i+1))-1);
   final.push(arrthis);
   return final;
 }
 }
 
 chunkArrayInGroups(["a", "b", "c", "d"], 2);
1 Like

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

So there are actually three problems here.

The first is this line: var arrthis = arr.slice(size*i, (size*(i+1))-1);

I think you put the -1 in there thinking that the slice returns one too many elements, but it doesn’t! So that should go.

More importantly, look where your return statement is, it’s inside the for loop! This means the for loop never gets past its first case!

Also, every time the for loop executes the body, final gets set to the empty array [], which means once you’ve fixed the previous two problems, it would still give only the final pair of elements. Fix this by moving the offending line outside of the for loop.