AniUI Academy

Chunk an array into fixed-size pieces

easyArrays & Objects+150 XPPractice

You have 47 product cards and a grid that shows three per row. Or 500 ids and an API that accepts 50 at a time. Both problems are the same problem: cut a flat array into consecutive pieces of a fixed size.

Implement chunk(items, size) returning a new array of arrays. Take items in order — the first size items, then the next size, and so on. The final piece is shorter than size when the items do not divide evenly.

Arguments

itemsArray
The flat input array to split.
sizenumber
The maximum length of each returned piece.

Returns

Array<Array> — A new nested array. Returns [] for an empty input, or when size is not a positive integer.

Examples

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

The final chunk is shorter when the length does not divide evenly.

chunk([1, 2, 3, 4], 2);  // [[1, 2], [3, 4]]
chunk([], 3);            // []
chunk([1, 2, 3], 0);     // []
chunk([1, 2, 3], -2);    // []

What it has to do

  • Return a new array of arrays, with items in their original order.
  • The last chunk holds the remainder when the length does not divide evenly.
  • Return [] when size is not an integer of at least 1.
  • Return [] for an empty input array.
  • Do not mutate the input array.
Asked atGoogleMeta

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.