DEV Community

Cover image for flatMap() vs filter().map(): Code Simplicity
Raja Jaganathan
Raja Jaganathan

Posted on

flatMap() vs filter().map(): Code Simplicity

When working with arrays, developers often use Array.filter().map() to transform data. But did you know Array.flatMap() can achieve the same result in a single step? Let’s explore when to use each.

Old Approach: filter().map() (Two Loops, Faster)

const persons = [
  { name: "Raja", age: 36 },
  { name: "Jaganathan", age: 65 },
  { name: "Kumar", age: 50 }
];

const result = persons.filter(p => p.age > 60).map(p => p.name);
console.log(result); // ["Jaganathan"]
Enter fullscreen mode Exit fullscreen mode

Here, .filter() first selects the matching objects, and then .map() extracts names. Though it involves two loops, modern JavaScript engines optimize it well, making it faster in many cases.

New Approach: flatMap() (Single Loop, More Readable)

const result = persons.flatMap(({ age, name }) => age > 60 ? [name] : []);
console.log(result); // ["Jaganathan"]
Enter fullscreen mode Exit fullscreen mode

With flatMap(), we combine filtering and mapping in one pass, making the code more concise. However, performance may slightly drop because flatMap() internally flattens arrays, adding overhead.

Performance Comparison

const persons = Array.from({ length: 1_000_000 }, (_, i) => ({
  name: `Person${i}`,
  age: Math.floor(Math.random() * 100)
}));

console.time("filter-map");
persons.filter(p => p.age > 60).map(p => p.name);
console.timeEnd("filter-map");

console.time("flatMap");
persons.flatMap(({ age, name }) => age > 60 ? [name] : []);
console.timeEnd("flatMap");
Enter fullscreen mode Exit fullscreen mode

filter-map: 18.2ms  
flatMap: 22.7ms  

Enter fullscreen mode Exit fullscreen mode

🔹 filter().map() is often faster because it avoids array flattening.
🔹 flatMap() is more concise, but has a small performance cost.

When to Use Each

✅ Use filter().map() when performance is critical.
✅ Use flatMap() when code simplicity matters more than micro-optimizations.

Both approaches are valid—it depends on your priority: speed or readability! 🚀

Happy Coding! 😊

Top comments (4)

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

Is it more readable though? I'm not sure about that.

Anyway, flatMap can be made to perform faster than .filter then .map if you are more careful with the array construction:

  • You don't need to wrap name in an array
  • You can use a single predefined dummy array in the empty result
const filter_out = []

persons.flatMap(({ age, name }) => age > 60 ? name : filter_out);
Enter fullscreen mode Exit fullscreen mode

Doing this improves the performance, so it becomes the fastest method. However, flatMap does not tell me you are doing a filter and a map; it tells me you are dealing with arrays of arrays, so I find the intent of the code requires significant parsing, which is probably not worth the 5% speed improvement.

Performance results: jsperf.app/baxase

Collapse
 
rajajaganathan profile image
Raja Jaganathan • Edited

Agreed flatMap has different purpose and semantic too. just illustrate for different use case.I miss the point of the unwanted array creation.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

As always, Mike making sense. Thanks for the insightful post.

I made an edition to your performance test because I think we should never lose sight of what plain JS can do: Version 2 of performance tests

As expected, plain JS beats them all.

Collapse
 
sathyamoorthi_p_65361ee6d profile image
Sathyamoorthi P

Good one Raja. Thx for introducing a new method with detailed performance reasoning.