Tell us what’s happening:
I’m currently trying to solve “Chunky Monkey” challenge.
I initialized result and sub array. Sub array (in theory) is resetted on each iteration and replaced by arr.slice(i, size).
Meanwhile, on each iteration, i is incremented by size
But the function only returns one correct sub-array.
For example, chunkArrayInGroups(["a", "b", "c", "d"], 2) returns [['a', 'b'], []]
And chunkArrayInGroups(["a", "b", "c", "d"], 1) returns [ [ 'a' ], [], [], [] ]
Does anyone see what I’m missing here?
**Your code so far**
function chunkArrayInGroups(arr, size) {
let result = []; // initializing result
let subArr = [];
for (let i = 0; i < arr.length; i+=size) {
subArr = arr.slice(i, size); // resetting subArr on each new iteration
result.push(subArr); // pushing subArr into result
}
return result;
}
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2)); // returns [['a', 'b'], []];
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36
I also tried declaring subArr inside the for loop:
function chunkArrayInGroups(arr, size) {
let result = []; // initializing result
for (let i = 0; i < arr.length; i+=size) {
let subArr = arr.slice(i, size); // resetting subArr on each new iteration
result.push(subArr); // pushing subArr into result
}
return result;
}
Congrats on solving this one.
I am sure Andrey’s hints and tips helped you and because of this you found his support helpful on your learning journey.
Unfortunately I did have to remove your final solution code from the forum because if someone else had found it, they would not have been able to learn from trial and error or even learn how to debug their own code (because they likely would just copy yours and move on).
I hope you understand this action and I again, congratulate you on a job well done!
ps. I also had to do the edit to another post that belongs to you. You may see me do that again in an older post as needed. If you would be so kind to remove any solutions you are aware of as well, that would be very helpful. (And if you see someone else post a solution, please flag it to the moderation team) Much appreciated!