# Basic Algorithm Scripting - Chunky Monkey

Tell us what’s happening:
Describe your issue in detail here.

I understand everything in this code except what is i + size?

``````  function chunkArrayInGroups(arr, size) {
let newArr = [];
let i = 0;

while (i < arr.length) {
newArr.push(arr.slice(i, i + size));
i += size;
}
return newArr;

}

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

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

Challenge: Basic Algorithm Scripting - Chunky Monkey

The size is the length of each “chunk” you want to push to your new array. If you called `chunkArrayinGroups([1,2,3,4,5,6], 2)`, you would get an array that looked like this:

``````[
[1,2],
[3,4],
[5,6]
]
``````

But if you called `chunkArrayinGroups([1,2,3,4,5,6], 3)`, you would get this:

``````[
[1,2,3],
[4,5,6]
]
``````

In order to do this, you need to repeatedly call arr.slice() with a starting index, ie 0, then the number of the index at which to stop slicing. That index should be equal to the starting number plus the size of the chunk you want. For example, in your code, `arr.slice(2,4)` will give you `["c", "d"]`, which is made up of the items at indexes 2 and 3.

When learning JS with these tutorials (or any time), it’s a good idea to output one or more test results to console.log like this: `console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));` Then you can see if it works at all, then play around with it to see what kind of output you get when you change the input.

EDIT: I’ve added some code to let you see what your method is doing at each step by outputting to the console:

``````function chunkArrayInGroups(arr, size) {
console.log(`Method called!
arr=[\${arr}]
size=\${size}`);
let newArr = [];
let i = 0;

console.log('Starting while loop...');
while (i < arr.length) {
console.log(`i=\${i} and i+size=\${i+size}
Pushing slice to new array: [\${arr.slice(i, i+size)}]`);
newArr.push(arr.slice(i, i + size));
i += size;
}
console.log(`All done!
Result: \${JSON.stringify(newArr)}`)
return newArr;

}

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

Try messing around with parameters in the last line until you understand what’s going on.

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