Skip to content

unicorn/prefer-array-flat Pedantic

🛠️ An auto-fix is available for this rule for some violations.

What it does

Prefers Array#flat() over legacy techniques to flatten arrays.

Why is this bad?

ES2019 introduced a new method Array#flat() that flatten arrays.

This rule aims to standardize the use of Array#flat() over legacy techniques to flatten arrays.

Example

Examples of incorrect code for this rule:

javascript
const foo = array.flatMap((x) => x);
const foo = array.reduce((a, b) => a.concat(b), []);
const foo = array.reduce((a, b) => [...a, ...b], []);
const foo = [].concat(maybeArray);
const foo = [].concat(...array);
const foo = [].concat.apply([], array);
const foo = Array.prototype.concat.apply([], array);
const foo = Array.prototype.concat.call([], maybeArray);
const foo = Array.prototype.concat.call([], ...array);

Examples of correct code for this rule:

javascript
const foo = array.flat();
const foo = [maybeArray].flat();

References

Released under the MIT License.