Q5: Chunk an Array into Sub-Arrays of Fixed Size

Split an array into smaller sub-arrays of a target size by iterating through the source array in increments of the chunk size and calling Array.prototype.slice().

Array Chunking Helper
function chunkArray(arr, size) {
  const chunked = [];
  for (let i = 0; i < arr.length; i += size) {
    chunked.push(arr.slice(i, i + size));
  }
  return chunked;
}

console.log(chunkArray([1, 2, 3, 4, 5], 2)); // [[1, 2], [3, 4], [5]]
💡 By incrementing the loop index by size each iteration, slice() extracts sub-arrays of exact length.
Key Takeaways
  • Advances loop pointer by size steps.
  • Array.prototype.slice extracts chunks cleanly without mutating the source array.
Knowledge Check

What is the result of chunkArray([1, 2, 3, 4, 5], 2)?