Chunk iterable
JavaScript, Function, Generator, Array · Mar 16, 2021

Chunks an iterable into smaller arrays of a specified size.
- Use a
for...of
loop over the given iterable, usingArray.prototype.push()
to add each new value to the currentchunk
. - Use
Array.prototype.length
to check if the currentchunk
is of the desiredsize
andyield
the value if it is. - Finally, use
Array.prototype.length
to check the finalchunk
andyield
it if it's non-empty.
const chunkify = function* (itr, size) {
let chunk = [];
for (const v of itr) {
chunk.push(v);
if (chunk.length === size) {
yield chunk;
chunk = [];
}
}
if (chunk.length) yield chunk;
};
const x = new Set([1, 2, 1, 3, 4, 1, 2, 5]);
[...chunkify(x, 2)]; // [[1, 2], [3, 4], [5]]
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.