Skip to main content

forEach

Selects items from an array, collection or enumerable object using a truth test and optionally invokes a function for each item.

Signature

forEach<T>(
list: T[] | undefined,
fn: (item: T) => boolean,
options?: {
do?: (item: T, ...arguments: any[]) => T | void;
replace?: boolean;
return?: "none" | "matches" | "first" | "last";
arguments?: any[];
}
): T[] | undefined

Parameters

NameTypeOptionalDescription
listT[] | undefinedNoSpecifies the array, collection or enumerable object to iterate through.
fn(item: T) => booleanNoSpecifies the selector function. Each item is supplied to the function, passing the item as argument. The function should return a boolean value whether to include the item in the selection.
optionsobjectYesSpecifies options for the iteration. Supports the following options:
- do: Specifies an optional function to be invoked for each element that passed the truth test. The element value will be exposed to the function as the first argument of the argument list. Additional arguments can be specified and will be pushed to the function;
- replace: Specifies if each value in the array should be overwritten with the return value of its executed function;
- return: Specifies if the function should return items. The default setting is matches which returns all items which pass the truth test;
- arguments: Optional additional arguments which will be passed to the callee.

Return value

Returns an array with the selected items or just the selected item if the single mode (first or last) is enabled.

Example

import { forEach } from "@tripetto/runner";

forEach<number>([1, 2, 3], (nItem: number) => nItem > 1); // Returns `[2, 3]`
forEach<number>([1, 2, 3], (nItem: number) => nItem > 1, {
do: (nItem: number) => nItem + 1,
replace: true
}); // Returns `[3, 4]`