Strange bug on Chunky Monkey

Tell us what’s happening:
My script is working but some of the tests done by the site end up with an empty array at the end.
For example:

(["a", "b", "c", "d"], 2) 
returns 
[ [ 'a', 'b' ], [ 'c', 'd' ], [] ]

While

([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)
returns
[ [ 0, 1 ], [ 2, 3 ], [ 4, 5 ], [ 6, 7 ], [ 8 ] ]

This behaviour is really strange and I don’t know what to make out of it.
Thanks in advance.

Your code so far

function chunkArrayInGroups(arr, size) {

  let knife = 0;
  let end = size;
  const result = [];
  let j = 0;
  
  for(let i = 0; i <= arr.length; i = i + size)
  {
    result[j] = arr.slice(knife, end);
    j++;
    knife = knife + size;
    end = end + size;
  }

  while(result.length >= arr.length)
  {
    result.pop()
  }
  console.log(result); 

  return result;
}

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

Your browser information:

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

Challenge: Basic Algorithm Scripting - Chunky Monkey

Link to the challenge:

Hmmm

Fascinating, I understand what happened now, it’s just really weird that it happened like it did.

The issue has been solved, thanks so much everyone.

I’d play around with it and see if you can see what happens. You sometimes do one extra loop iteration.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.