Chunk Array Lab
Create a JavaScript function that breaks an input array into smaller subarrays of specified length without using lodash's _.chunk
function.
Lab Description:
The goal of this lab is to write a function chunk
that takes an array arr
and a chunk size size
as input arguments and returns a chunked array. A chunked array contains the original elements in arr
, but it is divided into subarrays each of length size
. The length of the last subarray may be less than size
if arr.length
is not evenly divisible by size
.
You may assume the input array arr
is the output of JSON.parse
, meaning it is a valid JSON array.
Please solve this problem without using lodash's _.chunk
function.
Use ESM (ECMAScript Modules) import/export syntax everywhere in your code.
Examples:
-
If the input is
arr = [1, 2, 3, 4, 5], size = 1
, the output should be[[1], [2], [3], [4], [5]]
. Here, the input array has been split into subarrays with each having exactly 1 element. -
If the input is
arr = [1, 9, 6, 3, 2], size = 3
, the output should be[[1, 9, 6], [3, 2]]
. Here, the input array has been split into subarrays: the first subarray has 3 elements as persize = 3
, and the second subarray has only 2 elements remaining. -
If the input is
arr = [8, 5, 3, 2, 6], size = 6
, the output should be[[8, 5, 3, 2, 6]]
. In this case, the value ofsize
is greater than the length ofarr
, so all elements are placed in a single subarray. -
If the input is
arr = [], size = 1
, the output should be[]
. There are no elements to be chunked, so an empty array is returned.
Constraints:
arr
is a valid JSON array2 <= JSON.stringify(arr).length <= 105
1 <= size <= arr.length + 1
Challenges
- Challenge 1: Export the
chunk
function. - Challenge 2: Verify that your
chunk
function produces the expected output for various test cases.