To infinity and beyond

To infinity and beyond
0

#1

I’m getting an infinite loop warning on line 6. i can’t figure out why. My for loop is supposed to iterate through the array at the same intervals as the size argument. Then push the slice to my new array holder then once the iteration is done will return the new array.

Your code so far

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var array = [];
  for (var i = 0;i < arr.length;i + size) {
    array.push(arr.slice(0, size));
  } return array;
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36.

Link to the challenge:


#2

Your first mistake is that instead of using i += size (equivalent to i = i + size), you do i + size, which returns something you don’t want. next mistake is that you want the first parameter of arr.slice to be i, which starts at zero, and the second one, size + i instead of 0, size. So basically the first run i will be 0, size will be 2, next run, i will be i += size (0 + 2), and size will be size + i will be 2 + 2, 4. So that way, you will get the result you want, since the for loop while create an arrays of size “size” out of the array “arr” and push them to “array”.

If you want to use i++ instead of i += size and parameters (0, size). You will have to do arr.splice() instead of arr.slice(). arr.splice() removes the elements from the actual array unlike slice.

function chunkArrayInGroups(arr, size) {
  var array = [];
  for (var i = 0;i < arr.length;i **_+=_** size) {
    array.push(arr.slice**_(i, size + i_**));
  }
return array;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

#3

sorry for the bad formatting


#4

I fixed the formatting for you.