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;
}

function chunk(arr, size) {

const result = [];

for (let i = 0; i < arr.length; i += size) {

result.push(arr.slice(i, i + size));

}

return result;

}

Ah, the classic slice approach. Very direct.

The official solution will be up later today, for comparison.

Look. slice is usually the right tool for this kind of problem. No need to overcomplicate it.

Challenge solution: The task is to implement a function that splits an array into chunks of a specified size.

One way to do it:

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;
}

Why:
This solution iterates through the input array using a for loop, incrementing the index by ‘size’ in each step. In each iteration, it uses the ‘slice’ method to extract a sub-array from the current index up to ‘index + size’, effectively creating a chunk. These chunks are then pushed into a ‘result’ array, which is returned at the end, fulfilling the requirement of not mutating the original array.


Got it: @emmawalter5 :trophy:

First-answer leaderboard

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