Hey everyone I need some clarification and help understanding.
I have completed this challange but I would really like more help understanding it. Please don’t flame me to much for breaking this down as much as I am about to.
This was my original code for “Chunky Monkey”
function chunkArrayInGroups(arr, size) {
var newArray = [];
for (var i = 0, a= 0; i < arr.length; i++) {
newArray.push(arr.slice(a , size));
a += size;
size += size;
}
return newArray;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);
This returns this result: [[0,1][2,3][]]
I cannot understand why it did not return something else. In my head the code is saying this: step by step;
- We have a function.
- Hey I have an var which is ‘newArray’ and it equals ‘[]’
- Hey I have another var which is ‘loops’ and it equals ‘arr.length / size’
- Alright we are gonna do this ‘for’ loop.
- newArray now = newArray.push(arr.slice(0, 2));
a. newArray = newArray.push([0,1])
b. newArray = [[0,1]] - newArray now = newArray.push(arr.slice(2, 4));
a. newArray = newArray.push([2,3])
b. newArray = [[0,1],[2,3]] - newArray = newArray.push(arr.slice(4,6));
a. newArray = newArray.push([4,5]);
b. newArray = [[0,1],[2,3],[4,5]] - Alright im done with ‘for’ loop here s ‘newArray’ like you asked.
I don’t understand why it is not returning the last array as [4,5] and adding that to the end of the array it had before. Instead it returns []… I don’t get it at all.
Now this is the code that works, and I get it fully.
> function chunkArrayInGroups(arr, size) {
> var newArray = [];
> for (var i = 0; i < arr.length; i += size) {
> newArray.push(arr.slice(i , i + size));
> }
> return newArray;
> }
> chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);
Returns: [[0,1],[2,3],[4,5]]
So except for the fact that the working code looks cleaner then my original, I really don’t see why it would return a different outcome.
Thank you in advance for the help and clarification.