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 with 2 iteration: filter().map()
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 with 1 iteration: flatMap()
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
Multiple approaches have been tested on jsperf.app. Thanks @miketalbot and @webjose.
🔹 flatMap() vs filter().map() – There’s no clear winner, but flatMap() shows a slight performance advantage in some cases.
When to Use Each
✅ Use filter().map() when clarity and semantic intent are important.
✅ Use flatMap() when reducing iterations and simplifying code structure matters more than micro-optimizations.
Happy Coding! 😊
Good one Raja. Thx for introducing a new method with detailed performance reasoning.