Alternatives to .map(): .filter() and .flatMap()
What you'll learn: When to combine .filter() with .map() for conditional rendering, and when .flatMap() helps flatten nested arrays—all in the context of rendering React lists.
The Core Idea
While .map() transforms every item in an array, sometimes you need to selectively render items or flatten nested structures before rendering. That's where .filter() and .flatMap() shine.
Using .filter().map() for Conditional Rendering
When you only want to render some items from an array, chain .filter() before .map():
const products = [
{ id: 1, name: "Laptop", inStock: true },
{ id: 2, name: "Phone", inStock: false },
{ id: 3, name: "Tablet", inStock: true }
];
return (
<ul>
{products
.filter(product => product.inStock)
.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
This renders only in-stock products. Think of .filter() as a bouncer at a club—it checks each item and only lets matching ones through to .map().
Using .flatMap() for Nested Arrays
If your data has nested arrays and you want to render all items in a single flat list, use .flatMap():
const categories = [
{ name: "Fruit", items: ["Apple", "Banana"] },
{ name: "Veggies", items: ["Carrot", "Broccoli"] }
];
return (
<ul>
{categories.flatMap(category =>
category.items.map(item => <li key={item}>{item}</li>)
)}
</ul>
);
.flatMap() both transforms and flattens in one step—no need for separate .map() followed by .flat().
When to Use Each
.filter().map(): You have a simple array but need conditional rendering based on item properties.flatMap(): Your data is nested and you need a single flat list- Plain
.map(): Every item should render, no filtering or flattening needed
Key Takeaway: Use .filter().map() to conditionally render array items, and .flatMap() to flatten and render nested array structures—both are cleaner than inline conditional logic inside .map().