AphrodyBun GitHub

Runtime docs · Linter · Rules

unicorn/prefer-array-flat

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

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

Reported:

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

Not reported:

const items = pages.flat();

A flatMap that changes the elements isn't reported:

const tags = posts.flatMap(post => post.tags);