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.