0

There are a lots of examples of splitting an array into chunks, like this one: Split array into chunks, but I also wanted to keep the minimum size of each chunk, last chunk's size shouldn't be smaller than the expected minimum size.

Let's say you have an array with 1001 items, and you want to split into chunks of 100. The last chunk will became size of 1, in certain cases it might not be the expected result. So you also have minimum size of the chunk expected. What are the possible approaches?

Ahmet Cetin
  • 3,683
  • 3
  • 25
  • 34

1 Answers1

2

1. Drop the last chunk if it has less than minimum elements in it:

const chunk = (arr, size, min) => {
  const chunks = arr.reduce(
    (chunks, el, i) =>
      (i % size ? chunks[chunks.length - 1].push(el) : chunks.push([el])) && chunks,
    []
  );
  const l = chunks.length;

  if (chunks[l - 1].length < min) chunks.pop();
  return chunks;
};

2. Add last chunk to the previous chunk:

const chunk = (arr, size, min) => {
  const chunks = arr.reduce(
    (chunks, el, i) =>
      (i % size ? chunks[chunks.length - 1].push(el) : chunks.push([el])) && chunks,
    []
  );
  const l = chunks.length;

  if (chunks[l - 1].length < min) chunks[l - 2].push(...chunks.pop());
  return chunks;
};

3. Distribute last chunk into other chunks equally:

const chunk = (arr, size, min) => {
  const chunks = arr.reduce(
    (chunks, el, i) =>
      (i % size ? chunks[chunks.length - 1].push(el) : chunks.push([el])) && chunks,
    []
  );
  const l = chunks.length;

  if (chunks[l - 1].length < min) {
    const lastChunk = chunks.pop();
    let i = 0;

    while (lastChunk.length) {
      chunks[i % (l - 1)].push(lastChunk.pop());
      i += 1;
    }
  }

  return chunks;
};

Hope this helps.

Ahmet Cetin
  • 3,683
  • 3
  • 25
  • 34