Skip to content

Instantly share code, notes, and snippets.

@kolja
Created February 8, 2019 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kolja/c9aa038245e08652c8b5618b209d227c to your computer and use it in GitHub Desktop.
Save kolja/c9aa038245e08652c8b5618b209d227c to your computer and use it in GitHub Desktop.
split Arrays into chunks with Javascript
const split = (arr, fn) => arr.reduce(([first, ...rest],el) =>
fn(el)
? first.length ? [[], first, ...rest] : [[], ...rest]
: first.length ? [[...first, el], ...rest] : [[el], ...rest]
, [[]]).reverse()
const a = [...Array(12).keys()]
split(a, x => !(x%5))
// [ [ 1, 2, 3, 4 ], [ 6, 7, 8, 9 ], [ 11 ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment