Chunk an array into fixed-size pieces
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
[]whensizeis not an integer of at least 1. - Return
[]for an empty input array. - Do not mutate the input array.
Stuck? The javascript course covers everything this challenge needs.
- 1.splits into pieces with a short final chunk
- 2.divides evenly when the length is a multiple of size
- 3.returns an empty array for empty input
- 4.returns an empty array for an invalid size
- 5.does not mutate the input
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.