This rule raises an issue when Array.prototype.map() is immediately followed by Array.prototype.flat() with no arguments or a depth of 1.

Why is this an issue?

JavaScript’s Array.prototype.flatMap() method combines the functionality of map() and flat() in a single operation. When you chain .map().flat() or .map().flat(1), you’re performing two separate operations that could be done more efficiently and clearly with one.

The flatMap() method was specifically designed for this common pattern. It maps each element using a mapping function, then flattens the result by one level. This approach has several advantages:

The pattern .map().flat() is essentially reimplementing what flatMap() already does optimally.

What is the potential impact?

Using .map().flat() instead of .flatMap() creates unnecessary intermediate arrays, which can impact memory usage and performance, especially with large datasets. It also makes the code less readable and goes against JavaScript best practices.

How to fix?

Replace the chained .map().flat() calls with a single .flatMap() call. The mapping function remains the same.

Non-compliant code example

const result = items.map(item => transform(item)).flat(); // Noncompliant

Compliant code example

const result = items.flatMap(item => transform(item));

Documentation