Is this code solution correct?

Is this code solution correct?
0

#1

My question here is specifically about…
“For the first time it loops, it will look something like:
newArr.push(arr.slice(1, 1+2))

Shouldn’t it say …
newArr.push(arr.slice(0, 0+2))"

This is from the code solution wiki for the Chunky Monkey scripting algorithm that is on the free code camp github. The whole solution is below. My question is why does it say that the first loop through will have i = 1;
Where does that happen?

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr = [];
  var i = 0;

  while (i < arr.length) {
    newArr.push(arr.slice(i, i+size));
    i += size;
  }
  return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

Code Explanation:

Firstly, we create two variables. newArr is an empty array which we will push to. We also have the i variable set to zero, for use in our while loop.
Our while loop loops until i is equal to or more than the length of the array in our test.
Inside our loop, we push to the newArr array using arr.slice(i, i+size). For the first time it loops, it will look something like:

newArr.push(arr.slice(1, 1+2))

After we push to newArr, we add the variable of size onto i.
Finally, we return the value of newArr.


#2

I didn’t even know there was a code solution wiki. But you’re right, it is newArr.push(arr.slice(0, 0+2)) at the first iteration.

As it’s on GitHub and you found an issue, you can just create a pull request. :wink:


#3

I think the newArr.push(arr.slice(1, 1+2)) might be a typo.

Code

I pasted the code into repl.it, Chunky Monkey.

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr = [];
  var i = 0;

  while (i < arr.length) {
    
    console.log("i = " + i + " | (i+size) = " + (i+size));
    
    newArr.push(arr.slice(i, i + size));
    
    i += size;
    
  }// END WHILE
  
  return newArr;
  
}// END chunkArrayInGroups()

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

Results

You can see the first pass i equals 0.
Second pass, i equals 2.

i = 0 | (i+size) = 2
i = 2 | (i+size) = 4
=> [ [ 'a', 'b' ], [ 'c', 'd' ] ]

#4

Any Free Code Camp member can edit the wiki on the forum (which is the primary wiki not the GitHub one).