import { Meta } from '@storybook/addon-docs/blocks'

<Meta title='@dxtmisha/en/functional-basic/Functions/forEach - Iterate over an object or array'/>

# `forEach`

The function performs the specified function once for each element in the object. And returns an array with the results of executing the function.

**Parameters:**
- `data: D` — object for iteration.
- `callback: (item: T, key: K, dataMain: typeof data) => R` — a function to execute for each element in the array.
- `saveUndefined?: boolean` — if `true`, the function returns an array including `undefined` values (filtered by default).

**Returns:**
`R[]` — an array with the results of executing the function.

## How it works

The function is a universal tool for iterating over various data structures and collecting results into an array.

**Features:**
- **Type Support** — works with `Array`, `Map`, `Set`, and standard `Object`.
- **Result Collection** — unlike the standard `forEach`, this function collects the values returned from the `callback` into a new array.
- **Undefined Filtering** — by default, all `undefined` values (e.g., if the callback returned nothing for an element) are filtered out of the resulting array.
- **saveUndefined Parameter** — if `true` is passed as the third argument, the array will preserve all results, including `undefined`.

## Example

```typescript
import { forEach } from '@dxtmisha/functional-basic'

const data = [1, 2, 3]

// Undefined values are filtered by default
forEach(data, (item) => item % 2 === 0 ? item : undefined) // [2]

// With saveUndefined: true
forEach(data, (item) => item % 2 === 0 ? item : undefined, true) // [undefined, 2, undefined]
```
