API reference@evolu/commonArray › flatMapArray

Call Signature

function flatMapArray<T>(
  array: readonly [readonly [T, T], readonly [T, T]],
): readonly [T, T];

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

Maps each element to an array and flattens the result.

Preserves non-empty type when the input is non-empty and the mapper returns non-empty arrays. When called without a mapper, flattens nested arrays using identity.

Flattening and expanding values

import {
  assertEqual,
  assertType,
  flatMapArray,
  type NonEmptyReadonlyArray,
} from "@evolu/common";

const flattened = flatMapArray([
  [1, 2],
  [3, 4],
]);
const values: NonEmptyReadonlyArray<number> = [1, 2, 3];
const expanded = flatMapArray(
  values,
  (value, index): NonEmptyReadonlyArray<number> => [value, index],
);
assertEqual(flattened, [1, 2, 3, 4]);
assertType<NonEmptyReadonlyArray<number>, typeof expanded>();
assertEqual(expanded, [1, 0, 2, 1, 3, 2]);

Filter and map in one pass

Return [] to filter out, [value] to keep:

import { assertEqual, err, flatMapArray, ok } from "@evolu/common";

const validate = (value: number) =>
  value > 0 ? ok(value) : err(`${value} is not positive`);
const fields = [1, -2, 3, -4];
const errors = flatMapArray(fields, (f) => {
  const result = validate(f);
  return result.ok ? [] : [result.error];
});
assertEqual(errors, ["-2 is not positive", "-4 is not positive"]);

The mapper receives (item, index, array), matching native Array.flatMap.

Call Signature

function flatMapArray<T>(array: readonly (readonly T[][])): readonly T[];

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

Possibly empty nested arrays.

Call Signature

function flatMapArray<T, U>(
  array: readonly [T, T],
  mapper: (item: T, index: number, array: readonly T[]) => readonly [U, U],
): readonly [U, U];

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

Non-empty with mapper returning non-empty.

Call Signature

function flatMapArray<T, U>(
  array: readonly T[],
  mapper: (item: T, index: number, array: readonly T[]) => readonly U[],
): readonly U[];

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

With mapper function.