unicorn/prefer-array-flat-map
Require one .flatMap() instead of .map().flat() or .filter().flatMap()
fixable
.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#
example.js2 problems
const tags = posts.map(post => post.tags).flat()Array.flatMap performs Array.map and Array.flat in one step.;
const words = lines.map(line => line.split(" ")).flat(1)Array.flatMap performs Array.map and Array.flat in one step.;example.jsNo problems
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:
example.jsNo problems
const cells = tables.map(table => table.rows).flat(2);Children from React has a map but no flatMap, so it's left alone:
example.jsNo problems
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.
example.js1 problem
const points = lines.filter(line => line.visible).flatMapPrefer a single .flatMap(…) over .filter(…).flatMap(…).(line => [line.start, line.end]);example.jsNo problems
const points = lines.flatMap(line => line.visible ? [line.start, line.end] : []);