ChunkLoading saved progress…

Chunk

You have a long list of items and you want to lay them out in rows of three, or send them to an API that only accepts batches of 50, or paginate them ten per page. Chunking is the building block: split one flat array into many fixed-size groups. Lodash ships this as _.chunk — you're going to implement it.

Write a chunk function that takes an array and a size, and returns a new array of sub-arrays. Each sub-array has size elements, except the last one which holds whatever is left over.

Signature

function chunk(array, size) {
  // returns a new array of sub-arrays, each of length `size`
  // (the last sub-array holds the remainder)
}

Examples

chunk([1, 2, 3, 4, 5], 2);
// → [[1, 2], [3, 4], [5]]

chunk(['a', 'b', 'c', 'd'], 4);
// → [['a', 'b', 'c', 'd']]

Notes

  • Do not mutate the input array. Return a new array of new sub-arrays.
  • Empty inputchunk([], 3) returns [].
  • Size larger than length — return a single group containing every element.
  • Non-positive size — if size <= 0, return []. Don't loop forever.
  • No external libraries — implement it from scratch with the built-in array APIs.
Loading editor…