Skip to content

Instantly share code, notes, and snippets.

@danibrear
Created December 11, 2018 23:45
Show Gist options
  • Save danibrear/0fed039d14e3517346c9f369f319478e to your computer and use it in GitHub Desktop.
Save danibrear/0fed039d14e3517346c9f369f319478e to your computer and use it in GitHub Desktop.
Wanted to see if I could do it.
const chunk = (arr, size) => arr.reduce((a, n) => a[a.length-1].length < size ? [...a.slice(0,-1), [...a[a.length-1], n]] : [...a, [n]], [[]]);
const a = [1,2,3,4,5,6,7,8,9]
console.log(chunk(a, 2)); // -> [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
console.log(chunk(a, 3)); // -> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
console.log(chunk(a, 4)); // -> [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment