API reference / @evolu/common / Array / partitionArray
Function: partitionArray()
Defined in: packages/common/src/Array.ts:344
Partitions an array into two arrays based on a predicate or refinement function.
Returns a tuple where the first array contains elements that satisfy the predicate, and the second array contains elements that do not. Accepts both mutable and readonly arrays.
When used with a refinement function (with value is Type syntax),
TypeScript will narrow the first array to the narrowed type, making it useful
for filtering with Evolu Types like PositiveInt.is.
Examples
With predicate
const [evens, odds] = partitionArray([1, 2, 3, 4, 5], (x) => x % 2 === 0);
evens; // [2, 4]
odds; // [1, 3, 5]
With refinement
const mixed: ReadonlyArray<NonEmptyString | PositiveInt> = [
NonEmptyString.orThrow("hello"),
PositiveInt.orThrow(42),
];
const [positiveInts, strings] = partitionArray(mixed, PositiveInt.is);
// positiveInts: ReadonlyArray<PositiveInt> (narrowed type)
// strings: ReadonlyArray<NonEmptyString> (Exclude<T, PositiveInt>)
Type Parameters
| Type Parameter |
|---|
T |
S |
Parameters
| Parameter | Type |
|---|---|
array | readonly T[] |
refinement | RefinementWithIndex<T, S> |
Returns
readonly [readonly S[], readonly Exclude<T, S>[]]
Defined in: packages/common/src/Array.ts:348
Partitions an array into two arrays based on a predicate or refinement function.
Returns a tuple where the first array contains elements that satisfy the predicate, and the second array contains elements that do not. Accepts both mutable and readonly arrays.
When used with a refinement function (with value is Type syntax),
TypeScript will narrow the first array to the narrowed type, making it useful
for filtering with Evolu Types like PositiveInt.is.
Examples
With predicate
const [evens, odds] = partitionArray([1, 2, 3, 4, 5], (x) => x % 2 === 0);
evens; // [2, 4]
odds; // [1, 3, 5]
With refinement
const mixed: ReadonlyArray<NonEmptyString | PositiveInt> = [
NonEmptyString.orThrow("hello"),
PositiveInt.orThrow(42),
];
const [positiveInts, strings] = partitionArray(mixed, PositiveInt.is);
// positiveInts: ReadonlyArray<PositiveInt> (narrowed type)
// strings: ReadonlyArray<NonEmptyString> (Exclude<T, PositiveInt>)
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
array | readonly T[] |
predicate | PredicateWithIndex<T> |
Returns
readonly [readonly T[], readonly T[]]