Skip to content

Latest commit

Β 

History

History
98 lines (67 loc) Β· 1.91 KB

File metadata and controls

98 lines (67 loc) Β· 1.91 KB

prefer-array-flat

πŸ“ 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.

Examples

// ❌
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();

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

Related rules