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"]
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"]
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");
filter-map: 18.2ms
flatMap: 22.7ms
🔹 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)
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:name
in an arrayDoing this improves the performance, so it becomes the fastest method. However,
flatMap
does not tell me you are doing afilter
and amap
; 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
Agreed flatMap has different purpose and semantic too. just illustrate for different use case.I miss the point of the unwanted array creation.
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.
Good one Raja. Thx for introducing a new method with detailed performance reasoning.