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, 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[]];

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

Open Source Code