# unicorn/prefer-array-flat-map

> Require one `.flatMap()` instead of `.map().flat()` or `.filter().flatMap()`

`.map().flat()` builds an array of arrays only to take it apart again. `.flatMap()` does both in one pass, without the array in between.

`--fix` rewrites `.map(fn).flat()` to `.flatMap(fn)`.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"unicorn/prefer-array-flat-map" = "error" # or "warn"
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 2} */}
```js
const tags = posts.map(post => post.tags).flat();
const words = lines.map(line => line.split(" ")).flat(1);
```

Not reported:

{/* good */}
```js
const tags = posts.flatMap(post => post.tags);
const words = lines.flatMap(line => line.split(" "));
```

`.flatMap()` flattens one level, so a deeper `.flat()` isn't reported:

{/* good */}
```js
const cells = tables.map(table => table.rows).flat(2);
```

`Children` from React has a `map` but no `flatMap`, so it's left alone:

{/* good */}
```js
const items = React.Children.map(children, child => child.props.items).flat();
```

A `.filter()` before a `.flatMap()` that returns an array literal of two or more elements is also reported. The `.flatMap()` callback can return `[]` for the elements you want to skip. `--fix-suggestions` makes this change.

{/* bad */}
```js
const points = lines.filter(line => line.visible).flatMap(line => [line.start, line.end]);
```

{/* good */}
```js
const points = lines.flatMap(line => line.visible ? [line.start, line.end] : []);
```
