Explorer
JavaScript

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (use a loop that increments by size each iteration).
  3. Implement Logic: Handle state and transformations efficiently (use slice to extract sub-arrays of the given size).
  4. 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.

Array Chunk

Easy

Write a function chunk(arr, size) that splits an array into groups of the given size.

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

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[[[1,2],[3,4],[5]],[[1,2,3]]]