[SOLVED] Slice() from "Chunky Monkey" not working, unsure why

I have an issue as I work through the Chunky Monkey exercise in basic algorithms. Here’s my current code

function chunkArrayInGroups(arr, size) {

  var arrFormula = arr.length / size; // number of splits
  
  for (var i = 0; i <= arrFormula; i++) {
    sliced[i] = arr.slice(size * i, size + (size * i));
  }
  return sliced;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4);

So the part size + (size * i) should be returning 4, making arr.slice(0, 4) in the first loop. That should output [0, 1, 2, 3], but for some reason it’s only outputting [0, 1] and I can’t understand why.

It’s a bit difficult to tell what’s wrong without knowing what’s wrong with the output (please remember to always include code/outputs where applicable).

Anyhow! I noticed that you change the code just now to include size + and the extra comment you made. size + (size * 1) should not be a problem (the parentheses are not necessary because of the common order of operation.

The issue is, I think, because sliced is not defined before you used it. If you try console.log(sliced[0]), for example, you will see undefined. In fact, if you try to print something with console.log() right after sliced[i] = arr.slice(size * i, size + (size * i)); you will not get an output at all, meaning that the code never actually execute pass that line the first time.

There is another issue to your code that will give you an incorrect output (once you have fixed the issue with sliced). I believe you will be able to fix that, though! Come back if you need more help! :slight_smile:

EDIT Added ticks.

1 Like

Thank you for your help, that resolved the issue. Weird how it still was able to output something even without defining it beforehand.

I figured out the other error too (removing the = in i <=arrFormula.

Thanks again!

1 Like