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"] 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

Feb 22, 2025 - 05:54
 0
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"]

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