Basic Algorithm Scripting - Chunky Monkey

Tell us what’s happening:
the code is running perfectly so far, but whenever i set size to 8, it doesnt push the last element in the arr to x. how do i get it to complete the code

  **Your code so far**
function chunkArrayInGroups(arr, size) {
let x=[]
for(let i=0; i<arr.length+2; i++){

return x;

console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: Basic Algorithm Scripting - Chunky Monkey

Link to the challenge:

stop changing the array in the loop, that’s really bad practice and gives unexpected behaviour

I have added some console.log statements so you can see what the values of various variables are at different iterations of the for loop.

function chunkArrayInGroups(arr, size) {
  let x = []
  for (let i = 0; i < arr.length + 2; i++) {
    const chunk = arr.splice(0, size)
    console.log('chunk = ' + JSON.stringify(chunk))
    console.log('arr = ' + JSON.stringify(arr) )
    console.log('i = ' + i)
    console.log('arr.length + 2 = ' + (arr.length + 2) + '\n')
  return x

Stick with i < arr.length and rethink your logic. The problem is you are removing elements of the array but still incrementing i, so at some point i will not be less than size but you will still have elements left to remove.

You might be tempted to just change your i < arr.length + 2 and add a larger number of arr.length to get the challenge to pass but you should really design an approach to this problem where an array of any length and any size argument will pass.

I would recommend using slice instead of splice in your new approach, so you do not mutate the array passed to the function.