Skip to content

chunk() function

Returns Iterable/AsyncIterable of elements split into groups the length of size. If iterableIterator can't be split evenly, the final chunk will be the remaining elements.

Signature:

typescript
declare function chunk<T>(size: number, iterable: Iterable<T>): IterableIterator<T[]>;

Example

ts
const iter = chunk(2, [1, 2, 3, 4]);
iter.next() // {done:false, value:[1, 2]}
iter.next() // {done:false, value:[3, 4]}
iter.next() // {done:true, value: undefined}

// with pipe
pipe(
 [1, 2, 3, 4],
 chunk(2),
 toArray,
); // [[1, 2],[3, 4]]

await pipe(
 Promise.resolve([1, 2, 3 ,4]),
 chunk(2),
 toArray,
); // [[1, 2],[3, 4]]

// with toAsync
await pipe(
 [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4)],
 toAsync,
 chunk(2),
 toArray,
); // [[1, 2],[3, 4]]

Try It

see pipe, toAsync, toArray

Open Source Code

Released under the Apache-2.0 License.