Write a function `chunk(arr, size)` that splits an array into groups of the given size.
Problem Statement
<p>Write a function <code>chunk(arr, size)</code> that splits an array into groups of the given size.</p>
Examples
Input: arr = [1, 2, 3, 4, 5], size = 2
Output: [[1, 2], [3, 4], [5]]
Explanation: Array is split into subarrays of maximum size 2.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Use a loop that increments by size each iteration.
š” Hint 2:
Use slice to extract sub-arrays of the given size.
š” Hint 3:
for (let i = 0; i < arr.length; i += size) result.push(arr.slice(i, i + size));
Editorial & Approach
Problem Overview & Intuition
To solve Array Chunk, we consider the execution characteristics of JavaScript engines. Write a function `chunk(arr, size)` that splits an array into groups of the given size. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (use a loop that increments by size each iteration).
- Implement Logic: Handle state and transformations efficiently (use slice to extract sub-arrays of the given size).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function chunk(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
Complexity Analysis
Time Complexity
O(N) linear scan over input
Space Complexity
O(1) constant auxiliary space (or O(N) output)
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.