Chunk Array Lab

Easy
20
66.3% Acceptance

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:

  1. 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.

  2. 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 per size = 3, and the second subarray has only 2 elements remaining.

  3. 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 of size is greater than the length of arr, so all elements are placed in a single subarray.

  4. 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 array
  • 2 <= JSON.stringify(arr).length <= 105
  • 1 <= size <= arr.length + 1

Challenges

  1. Challenge 1: Export the chunk function.
  2. Challenge 2: Verify that your chunk function produces the expected output for various test cases.