Problem 53
Chunk Array Recursion Challenge
Given an array and a chunk size, divide the array into smaller subarrays of that size.
Function Signature
chunkArray(arr, size)
Parameters
arr— an array containing the values to divide into chunks.size— a positive integer representing the maximum length of each chunk.
Output
Return a new array where each element is a subarray containing elements from the original array.
Constraints
- The function must use recursion.
- Each subarray should have length equal to
size, except the last subarray may be shorter. - The input array must not be mutated.
- The function should always accept exactly two arguments.
Examples
chunkArray([1, 2, 3, 4, 5], 2) → [[1, 2], [3, 4], [5]]
chunkArray([1, 2, 3, 4, 5, 6], 3) → [[1, 2, 3], [4, 5, 6]]
chunkArray([1, 2, 3], 1) → [[1], [2], [3]]
chunkArray([], 3) → []
Edge Cases
- If the array length is not evenly divisible by
size, the final chunk contains the remaining elements. - If the input array is empty, return an empty array.
- If
sizeis larger than the array length, return one chunk containing the whole array.