Chunky Monkey Help!

Tell us what’s happening:
I just want this line of code explained more, I can’t get why it’s working. Hint #3 doesnt explain whats happening at all with this small piece of the code and I really think it should be, I have looked around to see why it produces the results it does, but I just can’t understand. Can someone please help me understand what I assume is a super basic concept that I am way over thinking?

This is the line I’d like explained, what im not getting is the first param being i, if i is 2, then nothing should work, so i isnt 2? is it 0, and the next i is 2? :

arr.slice(i,i + size)

function chunkArrayInGroups(arr, size) {

let newArr = [];

for(let i = 0;i < arr.length;i += size){

  let sliced = arr.slice(i,i + size);

  newArr.push(sliced);
  
} console.log(newArr)

return newArr

}

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

Please someone free me from my monkey brain.

  **Your browser information:**

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

Challenge: Chunky Monkey

Link to the challenge:

slice take two args, one where to start and one where to end.

slice returns a new array containing the elements between the first and second argument, but the second arguments index is excluded.

As an example:

const arr = [1, 2, 3];
console.log(arr.slice(0, 2)) // [1 , 2];
//3 was excluded as its index is 2

Something to note is that slice always returns a new array even if the index are beyond the length of the array, but if only the last index is greater than the array length the the new array will simply contain all elements starting from the first arg:

const arr = [1 , 2, 3];
console.log(arr.slice(10, 20)) // []
console.log([arr.slice(0, 100)]) //[1, 2, 3]

In your specific example the inside of the loop will look like:

//i === 0
let sliced = arr.slice(0, 0 + 2) // ["a", "b"];
newArr.push(sliced) //deepEquals(newArr, [["a", "b"]]) => true

//second iteration 

//i === 2
let sliced = arr.slice(2, 2 + 2) // ["c", "d"];
newArr.push(sliced) //deepEquals(newArr, [["a", "b"], ["c", "d"]]]) => true

The deepEquals function is not real, and simply means that the contents of the arrays are the same.

1 Like

The Information you shared above is great. I have been reading all you shared here. In this you explained everything very well. If i want any further guideline we will contact you here https://forum.freecodecamp.org/t/chunky-monkey-help/504904/.

Thank you very much for the thorough explanation. It has helped me greatly.

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