Help understanding this 'algorithm'?

Working on FCC right now, and on their basic algorithm problems. I've been struggling with every single one of them, and have had to look up the answers on more than I'd like to admit (depressing and demotivating).

I am currently on this one with the instructions:

Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.

Here is the 'basic' answer given (I couldn't figure this out on my own...again):

function chunkArrayInGroups(arr, size) {

  var temp = [];
  var result = [];

  for (var a = 0; a < arr.length; a++) {
    if (a % size !== size - 1)
      temp.push(arr[a]);
    else {
      temp.push(arr[a]);
      result.push(temp);
      temp = [];
    }
  }

  if (temp.length !== 0)
    result.push(temp);
  return result;
}

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

If possible, could someone explain how you get to the if (a % size !== size - 1 statement? Feeling too stupid to understand this...I am not sure what steps this person took in their brain to arrive at this (seemingly complex) statement. For instance, there is no way in hell I would have ever come to this same conclusion, without looking up their answer (hence the depression and demotivation).

Posted Jun 16, 2017, 7:01 PM UTC

313
Loading comments…