Tell us what’s happening:
I’m confused by the solution below. I’ve been going at this with the for loop and reduce()
- unsuccessfully - and all other types of approaches, but this while loop seems insufficient as proof for this even though it passes the test. I thought that the function should have a mechanism that identifies elements of the array and then associates them to the particular value of size and disseminates them accordingly.
The while loop doesn’t seem to do that at all. I mean, I’m sure it does, but I’m just overthinking the proof. I tried going through it at the bottom and it seems like it shouldn’t return the statement. The first test returns false and when I tried to make 0 >= 0
an insane result was returned so I stuck with what you have below.
I had a similar experience with splice()
. I was using slice()
to moderate success with some of attempts, passing a few tests. I was somewhat surprised that splice()
worked. This solution frustrates me. I know I can find a solution with for loop if I keep trying, but I’d just like to know why while loop works because it seems like it shouldn’t.
Could someone walk me through the logic or correct the logic I’m attempting to perform at the bottom of the page?
Thank you.
Your code so far
[spoiler]function chunkArrayInGroups(arr, size) {
//create empty array
var chunkArr = [];
//loop through arr collecting all elements larger than 0
while(arr.length > 0){
//as long as elements are larger than 0 push the extracted section of the array that is from index 0 to size limit of that particular subarray
chunkArr.push(arr.splice(0, size))
}
console.log(chunkArr);
return chunkArr;
}[/spoiler]
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3);
My attempt to follow the logic of the while loop.
0>0 false //no execution
1>0 true //chunkArr[1, 2, 3]
2>0 true //chunkArr[2, 3, 4]
3>0 true //chunkArr[3, 4, 5]
4>0 true //chunkArr[4, 5]
5>0 true //chunkArr[5]
So, I’m not clear at all why this works or why this is useful. It seems like it almost solves the problem by accident. Is it a legitimate solution or just an idiosyncrasy of the FCC console?
Thanks, Nick
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey/