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 Parameter | Description |
|---|---|
T | The type of the elements in the array. |
U | The type of the mapped values. |
Parameters
| Parameter | Type | Description |
|---|---|---|
arrayOrPromise | T[] | 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]