unicorn/prefer-array-flat

Require .flat() instead of flattening an array with concat, reduce or flatMap

fixable

concat, reduce and flatMap(x => x) can all flatten an array of arrays, but you have to work out that that's what they're doing. .flat() says so.

--fix rewrites the flatMap and reduce forms to .flat(). --fix-dangerously also rewrites [].concat.apply([], array). [].concat(...array) is reported, but you have to rewrite it yourself.

Configure#

Off by default. To turn it on:

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

Examples#

example.js5 problems
const a = pages.flatMap(items => items);
const b = pages.reduce((all, items) => all.concat(items), []);
const c = pages.reduce((all, items) => [...all, ...items], []);
const d = [].concat(...pages);
const e = [].concat.apply([], pages);
example.jsNo problems
const items = pages.flat();

A flatMap that changes the elements isn't reported:

example.jsNo problems
const tags = posts.flatMap(post => post.tags);