It skips some stuff, splice with for loop

Tell us what’s happening:

  **Your code so far**

function chunkArrayInGroups(arr, size) {
var newArr = [];
for (var i = -size; i < arr.length; i += size) {
newArr.unshift(arr.splice(i, size));
}
return newArr;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2));
console.log();
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15.

Challenge: Chunky Monkey

Link to the challenge:

You’re changing the size of the array as you loop over it, removing elements with splice. Say the array is length 4, so the code in the loop runs 4 times. When you’ve done 2 iterations, you’ve removed 2 elements, so the array is only length 2. But your loop is set up to keep going, end though there’s now nothing there

2 Likes

I tried to make
freeCodeCamp: Chunky Monkey. Write a function that splits an array… | by Nick Coleman | Medium
to a for loop.

This worked better except it didn’t work when it was too short.

function chunkArrayInGroups(arr, size) {
  var newArr = [];
  for (var i = 0; i <= arr.length; i++) {
newArr.push(arr.splice(0, size));
}
return newArr;
}

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

Just don’t use splice, use something that doesn’t alter the array you’re iterating over (hint: there is a method that does exactly this with one letter different to the one you’re using)

1 Like