API reference › @evolu/common › Array › flatMapArray
Call Signature
function flatMapArray<T>(
array: readonly [readonly [T, T], readonly [T, T]],
): readonly [T, T];
Defined in: packages/common/src/Array.ts:442
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 { 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],
);
expect(flattened).toEqual([1, 2, 3, 4]);
expectTypeOf(expanded).toEqualTypeOf<NonEmptyReadonlyArray<number>>();
expect(expanded).toEqual([1, 0, 2, 1, 3, 2]);
Filter and map in one pass
Return [] to filter out, [value] to keep:
import { 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];
});
expect(errors).toEqual(["-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:446
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:450
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:459
With mapper function.