Chunky Monkey - help pls

Tell us what’s happening:
I know the problem is that the Math.ceil method is returning the wrong number in the for loop’s condition but I don’t understand why that is. If I assign the condition to variable like x and use that variable as the condition, it works perfectly:

let x = Math.ceil(arr.length / size);
  for (let i = 1; i <= x; i++) {
    //push array of required size into returning array
    newArr.push(arr.splice(0, size));

How do I implement the Math.ceil method straight into the for loop’s condition without having to use a variable as a placeholder?

Your code so far

function chunkArrayInGroups(arr, size) {
  let newArr = [];
  for (let i = 1; i <= Math.ceil(arr.length / size); i++) {
    //push array of required size into returning array
    newArr.push(arr.splice(0, size));
  return newArr;

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:

It has to do with the side effects of the splice() method. Answer the questions below, and you’ll probably see what I mean:

  1. What is the length of arr at before you start the for loop?
  2. What is the length of arr after you’ve gone through the for loop 1 time?
  3. How does that affect the result of i <= Math.ceil(arr.length / size)?
1 Like

Oh my god, I feel so dumb haha. I can’t believe I didn’t see that. For some reason, I assumed the condition stays static once the loop starts. Thank you for the help!

Don’t feel bad. Loops can be difficult to reason about, especially at first. Glad you figured it out! Good luck going forward.

For what it’s worth, I don’t think I’d even use a for loop to solve this. I’d probably use a while loop to just keep breaking off chunks until the original array is empty.

1 Like

Damn that’s a good idea. Thanks again haha