API reference@evolu/commonArray › partitionArray

Call Signature

function partitionArray<T, S>(
  array: readonly T[],
  refinement: (item: T, index: number, array: readonly T[]) => item is S,
): readonly [readonly S[], readonly Exclude<T, S>[]];

Defined in: packages/common/src/Array.ts:766

Partitions an array into two readonly 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.

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.

With predicate

import { assertEqual, partitionArray } from "@evolu/common";

const [evens, odds] = partitionArray([1, 2, 3, 4, 5], (x) => x % 2 === 0);
assertEqual(evens, [2, 4]);
assertEqual(odds, [1, 3, 5]);

With refinement

import {
  assertEqual,
  assertType,
  NonEmptyTrimmedString,
  partitionArray,
  PositiveInt,
} from "@evolu/common";

const mixed: ReadonlyArray<NonEmptyTrimmedString | PositiveInt> = [
  NonEmptyTrimmedString.orThrow("hello"),
  PositiveInt.orThrow(42),
];
const [positiveInts, strings] = partitionArray(mixed, PositiveInt.is);
assertEqual(positiveInts, [42]);
assertType<ReadonlyArray<PositiveInt>, typeof positiveInts>();
assertType<ReadonlyArray<NonEmptyTrimmedString>, typeof strings>();

The predicate receives (item, index, array).

Call Signature

function partitionArray<T>(
  array: readonly T[],
  predicate: (item: T, index: number, array: readonly T[]) => boolean,
): readonly [readonly T[], readonly T[]];

Defined in: packages/common/src/Array.ts:771

With predicate.