Hone logo
Hone
Problems

Chunk Array into Groups

You're working on a data processing application where you need to divide a large array into smaller, manageable sub-arrays of a fixed size. This is a common task in scenarios like pagination, batch processing, or when sending data in chunks over a network. Your challenge is to implement a JavaScript function that efficiently performs this array chunking.

Problem Description

Implement a JavaScript function named chunkArray that takes two arguments:

  1. arr: The array to be chunked.
  2. chunkSize: A positive integer representing the desired size of each chunk.

The function should return a new array containing sub-arrays (chunks) of the original array. Each chunk should have a maximum size of chunkSize. The last chunk may be smaller than chunkSize if the original array's length is not perfectly divisible by chunkSize.

Key Requirements:

  • The function must return a new array; it should not modify the original array.
  • Each sub-array in the output must have a length less than or equal to chunkSize.
  • The order of elements within the chunks must be preserved from the original array.
  • The function should handle cases where chunkSize is greater than the length of the input array.

Expected Behavior:

Given an array and a chunk size, the function should produce an array of arrays.

Edge Cases to Consider:

  • An empty input array.
  • A chunkSize of 1.
  • A chunkSize that is larger than the input array's length.
  • An input array with a length that is not a multiple of chunkSize.

Examples

Example 1:

Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9], chunkSize = 3
Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Explanation: The array is split into chunks of size 3.

Example 2:

Input: arr = ['a', 'b', 'c', 'd', 'e'], chunkSize = 2
Output: [['a', 'b'], ['c', 'd'], ['e']]
Explanation: The last chunk contains the remaining element.

Example 3:

Input: arr = [10, 20, 30], chunkSize = 5
Output: [[10, 20, 30]]
Explanation: The chunk size is larger than the array length, so the entire array becomes a single chunk.

Example 4:

Input: arr = [], chunkSize = 4
Output: []
Explanation: An empty input array results in an empty output array.

Constraints

  • 0 <= arr.length <= 10^5
  • 1 <= chunkSize <= 10^5
  • arr will only contain elements of primitive types (numbers, strings, booleans, null, undefined) or simple objects.
  • The solution should aim for an efficient time complexity, ideally O(n), where n is the length of the input array.

Notes

Consider using array methods like slice() or iterating through the array with a loop and keeping track of the current index. Pay attention to how you handle the end of the array to ensure the last chunk is correctly formed.

Loading editor...
javascript