




Sponsored
Sponsored
This approach involves iterating over the array using a loop and extracting subarrays using slicing. The loop increments by the chunk size in each iteration, thus effectively slicing the array into chunks of the desired size.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n), storing the entire chunked array requires space proportional to the input size.
1The chunkArray function iterates through the array by incrementing by size. In each iteration, a subarray is created by slicing the array from index i to i + size and pushed to result.
This approach uses simple arithmetic operations to determine when to create a new subarray. Using the modulus operator allows checking if the number of currently collected elements is equal to the chunk size, upon which a new subarray is started.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n), because the additional space needed is proportional to the input size.
1function chunkArray(arr, size) {
2    const chunked = [];
3    let chunk = [];
4    arr.forEach((elem) => {
5        chunk.push(elem);
6        if (chunk.length === size) {
7            chunked.push(chunk);
8            chunk = [];
9        }
10    });
11    if (chunk.length > 0) chunked.push(chunk);
12    return chunked;
13}This solution uses forEach to iterate over the array elements, collecting elements in chunk. Once chunk reaches the specified size, it is pushed to chunked and reset. Any remaining elements in chunk are added at the end.