0
votes

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?

1
Possible duplicate of Split array into chunksUser863
Well, kinda, but there is no solution with minimum chunk size.Ahmet Cetin
Why ask a question to immediately answer it?kemotoe
it's a feature in stackoverflow to share knowledge, there is a checkbox to answer the question immediately. i just ran into such requirement, and i wanted to share.Ahmet Cetin

1 Answers

2
votes

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.