Coding Challenge - #30: Chunk Array Elements

Write a function chunk(arr, size) that splits an array into groups of length size and returns them as a two-dimensional array. If the array cannot be split evenly, the final chunk should contain the remaining elements. For example, chunk([1, 2, 3, 4, 5], 2) should return [[1, 2], [3, 4], [5]].

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

Rules:

  • Return an empty array if the input array is empty.
  • Assume size is always an integer greater than 0.
  • Do not mutate the original input array.

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

This is a classic problem. I remember a similar one from a data visualization project where I needed to group data points for a small multiples chart.

function chunk(arr, size) {
  if (arr.length === 0) {
    return [];
  }

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