Hone logo
Hone
Problems

Chunking Arrays into Groups in JavaScript

This challenge focuses on a common array manipulation task: dividing an array into smaller, evenly sized chunks. Chunking arrays is useful for tasks like splitting large datasets for parallel processing, formatting data for display in a grid, or preparing data for API requests with size limitations. Your task is to write a JavaScript function that takes an array and a chunk size as input and returns a new array containing the chunked array elements.

Problem Description

You need to create a function called chunkArray that accepts two arguments:

  • array: The input array that needs to be chunked. This array can contain any data type.
  • chunkSize: The desired size of each chunk. This will be a positive integer.

The function should return a new array where the original array has been divided into chunks of the specified chunkSize. If the original array's length is not perfectly divisible by chunkSize, the last chunk should contain the remaining elements.

Key Requirements:

  • The function must return a new array; it should not modify the original array.
  • Each element of the returned array should be an array representing a chunk.
  • The chunks should be created in the order of the original array.

Expected Behavior:

The function should handle various scenarios, including:

  • Empty input array.
  • chunkSize of 1.
  • chunkSize equal to the array length.
  • chunkSize larger than the array length.
  • Arrays with different data types.

Examples

Example 1:

Input: [1, 2, 3, 4, 5], 2
Output: [[1, 2], [3, 4], [5]]
Explanation: The array is divided into chunks of size 2. The last chunk contains the remaining element (5).

Example 2:

Input: [1, 2, 3, 4, 5, 6, 7, 8], 3
Output: [[1, 2, 3], [4, 5, 6], [7, 8]]
Explanation: The array is divided into chunks of size 3.

Example 3:

Input: [1, 2, 3], 5
Output: [[1, 2, 3]]
Explanation: The chunk size is larger than the array length, so the entire array forms a single chunk.

Example 4:

Input: [], 2
Output: []
Explanation: An empty array results in an empty array.

Constraints

  • array will be an array of any data type.
  • chunkSize will be a positive integer (greater than 0).
  • The function should be efficient enough to handle arrays with up to 10,000 elements without significant performance degradation.

Notes

Consider using a loop or array methods like slice() to create the chunks. Think about how to handle the case where the array length is not evenly divisible by the chunk size. A for loop with appropriate indexing is a common and efficient approach. Avoid modifying the original array.

Loading editor...
javascript