Chunky Monkey | Works, but over complicated

Chunky Monkey | Works, but over complicated
0.0 0

#1

Hi guys, actually I meneged to solve this problem, but it feels over complicated.
Can any of you advise me where and how can I make this more simple?
Thanks in advance for your effort! =)

Here is the code for the Chunky Monkey:


function chunkArrayInGroups(arr, size) {
  var ans = [];
  var i = 0;
  while ( arr.length > 0 ) { 
    ans[i] = [];
//filling up the subArray
    for (var k = 0; k < size; k++) {
      ans[i].push(arr.shift());  
// Return whatever we have, because no more elements left in [arr]
      if (arr.length < 1) {
        return ans;
      } 
    }
    i++;
  }
  return ans;
}

#2

Consider exactly what shift does, as opposed to slice. Then, consider how slice differs from splice, and think about how you could reduce the number of variables in play.


#3

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.


#4

Sorry for that, next time I’ll do it like that, but on the other hand, the title of this post is straight forward. But I know, rules are rules.


#5

Thanks for the path, I reworked my code according your lead. Now it looks as I expected.

Here it is:


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

chunkArrayInGroups(["a", "b", "c", "d"], 2);ste code here

#6

Nice job! That’s almost exactly the same as the advanced solution on the guide :smile: