Skip to content Skip to sidebar Skip to footer

Splitting An Array Up Into Chunks Of A Given Size With A Minimum Chunk Size

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

Solution 1:

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.


Post a Comment for "Splitting An Array Up Into Chunks Of A Given Size With A Minimum Chunk Size"