Skip to content
NewBun 1.4.5 is out. Release notes
AphrodyBun

Linter · Rules

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).

Configure

Off by default. To turn it on:

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

Examples

Reported:

const tags = posts.map(post => post.tags).flat();
const words = lines.map(line => line.split(" ")).flat(1);

Not reported:

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:

const cells = tables.map(table => table.rows).flat(2);

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

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.

const points = lines.filter(line => line.visible).flatMap(line => [line.start, line.end]);
const points = lines.flatMap(line => line.visible ? [line.start, line.end] : []);