Skip to content

Latest commit

 

History

History
107 lines (76 loc) · 1.88 KB

prefer-array-flat.md

File metadata and controls

107 lines (76 loc) · 1.88 KB

Prefer Array#flat() over legacy techniques to flatten arrays

💼 This rule is enabled in the ✅ recommended config.

🔧 This rule is automatically fixable by the --fix CLI option.

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

Fail

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);
const foo = _.flatten(array);
const foo = lodash.flatten(array);
const foo = underscore.flatten(array);

Pass

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

Options

Type: object

functions

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

Related rules