π Prefer Array#flat() over legacy techniques to flatten arrays.
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π§ This rule is automatically fixable by the --fix CLI option.
ES2019 introduced a new method Array#flat() that flatten arrays.
// β
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(...array);
// β
const foo = [].concat.apply([], array);
// β
const foo = Array.prototype.concat.apply([], array);
// β
const foo = Array.prototype.concat.call([], ...array);
// β
const foo = _.flatten(array);
// β
const foo = lodash.flatten(array);
// β
const foo = underscore.flatten(array);
// β
const foo = array.flat();// β
const foo = [].concat(maybeArray);
// β
const foo = Array.prototype.concat.call([], maybeArray);
// β
const foo = [maybeArray].flat();Type: object
Type: string[]
You can also check custom functions that flatten arrays.
_.flatten(), lodash.flatten(), and underscore.flatten() are always checked.
Example:
{
'unicorn/prefer-array-flat': [
'error',
{
functions: [
'flatArray',
'utils.flat'
]
}
]
}/* eslint unicorn/prefer-array-flat: ["error", {"functions": ["utils.flat"]}] */
// β
const foo = utils.flat(bar);