Chunk iterable

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

Chunks an iterable into smaller arrays of a specified size.

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.

More like this

  • JavaScript Arrays

    Master array manipulation in JavaScript with this ES6 snippet collection.

    Collection · 210 snippets

  • Using JavaScript generator functions for ranges

    Learn how to use JavaScript ES6 generators and iterators to iterate over ranges of numbers.

    JavaScript, Function · Jun 12, 2021

  • Unfold array

    Builds an array, using an iterator function and an initial seed value.

    JavaScript, Function · Sep 15, 2020

  • Generator to array

    Converts the output of a generator function to an array.

    JavaScript, Function · Dec 31, 2020