Skip to main content

compactMap

Functions​

compactMap()​

compactMap<T, U>(arrayOrPromise, callbackfn): Promise<U[]>

Maps each element of an array to a new value and filters out null and undefined values.

Type Parameters​

Type ParameterDescription
TThe type of the elements in the array.
UThe type of the mapped values.

Parameters​

ParameterTypeDescription
arrayOrPromiseT[] | Promise<T[]>An array or a promise that resolves to an array.
callbackfn(value, index, array) => undefined | null | U | Promise<undefined | null | U>A function that maps each element of the array to a new value. If the function returns null or undefined, the value is filtered out.

Returns​

Promise<U[]>

A promise that resolves to an array of mapped values.

Example​

const array = [1, 2, 3, 4, 5];
const result = await compactMap(array, (value) =>
value % 2 === 0 ? value * 2 : null
);
console.log(result); // [4, 8]

Defined in​

src/compactMap/index.ts:21