Basic Algorithm Scripting: Chunky Monkey // For Vs. While loop

Tell us what’s happening:
How do i get the rest of the arr into the newArr? I tried the spread operator but then it would return the whole original array.

Looking at the solutions. How is it different than the while loop used here?

  var newArr = [];
  while (arr.length) {
    newArr.push(arr.splice(0, size));
  }
  return newArr;
}

I’m thinking that the for and while loops are kind of the same. The for loop made sense to me because it would iterate through elements of the array. The while loop, i’m not understanding so much. Once the arr is spliced, the arr.length would no longer apply?

Please help

Your code so far


function chunkArrayInGroups(arr, size) {
// Break it up.
let newArr = [];
for (let i = 0; i < arr.length; i++) {
  let subArr = arr.splice(0 ,size)
  newArr.push(subArr)
  
}
return newArr;
}

console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36.

Challenge: Chunky Monkey

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey

size is 3, so 3 elements are removed at each iteration. length of the array is 7

i is 0, length is 7
i is less than 7, so length becomes 4
i is 1, length is 4
i is less than length, length becomes 1
i is 2, length is 1
i is not less than length, the loop stops
but there are still elements that need to be added to the chunked array

see the issue?

1 Like

I see the issue with the loop! yes Thank you! for the while loop, it doesn’t have a condition to compare to, so it just has whatever length arr is everytime its spliced right?

yes, with the caveat that when arr.length reaches 0 then it is a falsy value and the while loop stops
wanting it more clear you can write arr.length > 0 and it does the same
thing

1 Like