Coding Challenge - #12: Chunk An Array

Write a function chunk(arr, size) that splits an array into smaller sub-arrays of a specified length. For example, chunk([1, 2, 3, 4, 5], 2) should return [[1, 2], [3, 4], [5]].

function chunk(arr, size) {
  // Your code here
}

Rules:

  • Must return a new array of chunked arrays.
  • The final chunk can contain fewer elements if the input array cannot be divided evenly.
  • Do not use any external libraries.

Post your solution as a reply. Answer goes up in about a day.

A simple approach is to step through the array by the chunk size and use slice():

function chunk(arr, size) {
  const result = [];

  for (let i = 0; i < arr.length; i += size) {
    result.push(arr.slice(i, i + size));
  }

  return result;
}

For example:

chunk([1, 2, 3, 4, 5], 2);
// [[1, 2], [3, 4], [5]]

This keeps the original array unchanged and naturally handles the final smaller chunk.

nice, slicing is definitely a good way to approach this. we’ll see how close that gets you later today!

Yeah slice() is definitely the move here. way cleaner than trying to loop through and manage indices manually.

Challenge solution: The task requires splitting an array into sub-arrays of a given size, handling cases where the last sub-array might be smaller.

One way to do it:

function chunk(arr, size) {
  const chunkedArr = [];
  let index = 0;

  while (index < arr.length) {
    chunkedArr.push(arr.slice(index, index + size));
    index += size;
  }

  return chunkedArr;
}

Why:
This solution iterates through the input array using a while loop and an index. In each iteration, it uses the slice method to extract a sub-array of the specified ‘size’ and pushes it into the ‘chunkedArr’. The index is then incremented by ‘size’ to move to the next chunk’s starting point, ensuring all elements are processed and the last chunk correctly handles remaining elements.


Got it: @Apexcodes :trophy:

First-answer leaderboard

  1. @kirupa - 6 (firsts) :trophy:
  2. @Apexcodes - 5 (firsts)
  3. @adnanahmed - 2 (firsts)
  4. @emmawalter5 - 2 (firsts)

This is a perfectly functional approach. My main concern with slice in a loop like this is often performance on very large arrays, though for typical challenge sizes it’s negligible. I’ve seen some solutions use reduce to build up the chunks, which can be a bit more declarative, but often less immediately clear than a while loop with an explicit index. Confidence: high