Skip to main content

partition

partition() function

Split Iterable/AsyncIterable into two arrays: one with all elements which satisfies f and the other with all elements that does not.

Signature:
declare function partition<A, B>(f: (a: A) => B, iterable: Iterable<A>): [A[], A[]];

declare function partition<A, B>(f: (a: A) => B, iterable: AsyncIterable<A>): Promise<[A[], A[]]>;

declare function partition<A extends Iterable<unknown> | AsyncIterable<unknown>, B>(f: (a: IterableInfer<A>) => B): (iterable: A) => ReturnPartitionType<A>;

Example

partition((a) => a % 2 === 0, [1, 2, 3, 4, 5]); // [[2, 4], [1, 3, 5]]

// with pipe
pipe(
[1, 2, 3, 4, 5],
partition((a) => a % 2 === 0), // [[2, 4], [1, 3, 5]]
);

await pipe(
Promise.resolve([1, 2, 3, 4, 5]),
partition((a) => a % 2 === 0), // [[2, 4], [1, 3, 5]]
);

// if you want to use asynchronous callback
await pipe(
Promise.resolve([1, 2, 3, 4, 5]),
toAsync,
partition(async (a) => a % 2 === 0), // [[2, 4], [1, 3, 5]]
);

// with toAsync
await pipe(
[Promise.resolve(1), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4), Promise.resolve(5)],
toAsync,
partition((a) => a % 2 === 0), // [[2, 4], [1, 3, 5]]
);

Try It

see pipe, toAsync