Skip to content

Chunky Monkey

Islam Ibakaev edited this page Apr 26, 2016 · 1 revision

Details

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.

Elegant Solution

function chunkArrayInGroups(arr, size) {
  return arr.length > size ? [arr.splice(0, size)].concat(chunkArrayInGroups(arr, size)) : [arr];
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3); // returns [[0, 1, 2], [3, 4, 5]]
Clone this wiki locally