← Back to libraryQuestion 164 of 468
🧩JavaScript CodingIntermediate

Chunk an Array

📌 Definition:

Split an array into groups (chunks) of a given size, e.g. chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]].

📖 Detailed Explanation:

Iterate in steps of size, slicing each window. slice safely handles the final partial chunk. Guard against size <= 0.

💻 Solutions:
function chunk(arr, size) {
  if (size <= 0) throw new Error('size must be > 0');
  const out = [];
  for (let i = 0; i < arr.length; i += size) {
    out.push(arr.slice(i, i + size));
  }
  return out;
}
🔑 Key Points:
  • Step the index by 'size' and slice each window
  • slice(i, i+size) handles the last partial chunk automatically
  • Validate size > 0 to avoid an infinite loop
  • O(n) time
🌍 Real-World Example:

Chunking batches API calls (send 100 records at a time) and paginates test data so you don't overload a service during load testing.

🎯 Scenario-Based Interview Question:

chunk(arr, 0) hangs the process. Why, and how do you prevent it?