Lesson 3 of 8
Splitting into chunks
- 11 min
- 6 checks
- 3 hints
- Go to task
Goal
A thousand items in batches of a hundred
Explanation
Paginating results, sending data in batches and laying out items in a three-column grid all come down to the same thing: splitting an array into groups of a fixed size.
The slice method does this without changing the original array: you move forward in steps of size and cut out one piece at each step.
The real test is the edge cases: an empty array, a size that doesn't divide the length evenly, and a size of zero or less. That last one makes the loop run forever if you don't check for it before the loop starts.
Your task
Write chunk(arr, size) to return an array of arrays, after first checking that the input is valid.
Checks
6 checks- Splits into equal chunks correctly
- The shorter last chunk isn't lost
- An empty array returns an empty array
- A size of zero doesn't freeze the page
- A negative size doesn't freeze the page either
- The original array is unchanged