Skip to content

Latest commit

 

History

History
57 lines (40 loc) · 2.12 KB

File metadata and controls

57 lines (40 loc) · 2.12 KB

prefer-array-flat-map

📝 Prefer .flatMap(…) over .map(…).flat() and .filter(…).flatMap(…).

💼 This rule is enabled in the following configs: ✅ recommended, ☑️ unopinionated.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Array#flatMap performs Array#map and Array#flat in one step.

It can also add or remove items during mapping by returning an empty array for items that should be skipped. This rule only reports .filter().flatMap() when the .flatMap() callback can return multiple items. Single-item callbacks are handled by unicorn/no-unnecessary-array-flat-map.

Examples

// ❌
const foo = bar.map(element => unicorn(element)).flat();

// ❌
const foo = bar.map(element => unicorn(element)).flat(1);

// ✅
const foo = bar.flatMap(element => unicorn(element));
// ❌
const foo = bar
	.filter(element => element.isUnicorn)
	.flatMap(element => [element.name, element.alias]);

// ✅
const foo = bar.flatMap(element => element.isUnicorn ? [element.name, element.alias] : []);
// ✅
const foo = bar.map(element => unicorn(element)).flat(2);
// ✅
const foo = bar.map(element => unicorn(element)).foo().flat();
// ✅
const foo = bar.flat().map(element => unicorn(element));

Related rules