Dev HelpersOpen library
← Back

Chunk an array

Chunk an array. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const chunk = (xs, n) =>
  Array.from({ length: Math.ceil(xs.length / n) }, (_, i) =>
    xs.slice(i * n, (i + 1) * n),
  );
console.log(chunk([1, 2, 3, 4, 5], 2));

Sample output

[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]