Implement the Chunky Monkey Algorithm - Implement the Chunky Monkey Algorithm

Tell us what’s happening:

Hi,

I don’t understand what I am doing wrong. Why does it skip ‘dog’ for example?

I really need som hints!!
thanks

Your code so far

function chunkArrayInGroups(array, num) {
    for (var i = 0; i <= array.length; i++) {
    console.log(array[i])
    var spliced = array.splice(i, num);
    console.log(spliced);
  }
  let bigArr = [spliced];
  return bigArr;
 }

let array = ['cat', 'banana', 'dog', 'mustard', 'lion'];
let num = 2;


console.log(chunkArrayInGroups(array, num))

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:148.0) Gecko/20100101 Firefox/148.0

Challenge Information:

Implement the Chunky Monkey Algorithm - Implement the Chunky Monkey Algorithm

Try looking at the array within the for loop during each iteration, ie.:

console.log(i, array)

It’s never a good idea to change the contents of an array you are looping over. And do you really want the loop variable to ever be equal to the array length?

I did that now, the array shows up in every iteration. I’m really scratching my head at this.. do you have any other suggestions? :head_shaking_vertically:

ohh and why so? Should I then change the array outside of the loop?

Removed i <= array.length and changed it to i <= num

because when you remove items from the array while iterating over it, you get unexpected situations

like, let’s say array [2,4,5,6,8], we want to remove an element when it’s even

at first iteration, i=0
so we look at index 0, the 2 here is even, so we remove it

now the array is [4,5,6,8]
second iteration, i=1
so we look at index 1, there is a 5, this is odd, so we keep it

do you see what went wrong here?

2 Likes