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>;

declare function partition<A, L extends A, R extends A = A extends object ? ExcludeObject<A, L> : Exclude<A, L>>(f: (a: A) => a is L, iterable: Iterable<A>): [L[], R[]];

declare function partition<A, L extends A, R extends A = A extends object ? ExcludeObject<A, L> : Exclude<A, L>>(f: (a: A) => a is L, iterable: AsyncIterable<A>): Promise<[L[], R[]]>;

declare function partition<A extends Iterable<unknown> | AsyncIterable<unknown>, B extends IterableInfer<A>, L extends B, R extends B = B extends object ? ExcludeObject<B, L> : Exclude<B, L>>(f: (a: IterableInfer<A>) => a is L): (iterable: A) => A extends AsyncIterable<any> ? Promise<[L[], R[]]> : [L[], R[]];

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