Coding

Chunk Algorithm

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.


Example:
chunk([“a”, “b”, “c”, “d”], 2) ==> [[ “a”, “b”], [“c”, “d”]]
chunk([0, 1, 2, 3, 4, 5], 4) ==> [[0, 1, 2, 3], [4, 5]]

const chunk = (array, size) => {
  const resultArray = []

  for (let i = 0; i < array.length; i ++) {
    let item = array[i]
    let last = resultArray[resultArray.length - 1]

    if (!last || last.length === size) {
      resultArray.push([item])
    } else {
      last.push(item)
    }
  }

  return resultArray
}