Chunk an array
beginner Arrays Challenge 1 of 18
Write chunk(arr, size), which splits arr into consecutive groups of size elements. The last group holds whatever is left over. A common real use is splitting a list of test accounts or test files into batches.
Requirements
- Return a new array of arrays, in the original order.
- The last chunk may be shorter than
size. - An empty input returns
[]. - Do not mutate
arr. - Throw an error when
sizeis not a positive integer (for example0or-1).
Expected output
chunk([1,2,3,4,5], 2) → [[1,2],[3,4],[5]] chunk([], 3) → [] chunk([1,2], 0) → throws RangeError
Test cases (6)
- ○splits with a remainder
- ○splits evenly
- ○size larger than the array gives one chunk
- ○empty array gives no chunks
- ○does not mutate the input
- ○rejects a size below 1
solution.jsExecutes in your browser
function chunk(arr, size) {
// TODO: return a new array of chunks
}
Ctrl/⌘ + Enter to run tests · your code is saved in this browser
Results
Run the tests to see results here.