Map, Filter, Reduce in Depth
Mastering functional array transformation, filtering, and accumulation patterns.
What you'll learn
- map: transforming every element into a new array
- filter: keeping elements that pass a predicate
- reduce: accumulating all elements into one value
- Chaining map/filter/reduce for data pipelines
- Common pitfalls: forgetting the initial value and mutating in callbacks
Concept
The Functional Trio
map, filter, and reduce are the three foundational functional array methods. They treat arrays as data to transform, not as mutable storage to modify in place. Each returns a new array (or value for reduce), leaving the original untouched. This immutability makes code easier to reason about and is the backbone of modern data processing in React, Node, and functional libraries.
map — Transform
map(fn) applies fn to every element and returns a new array of the same length. The callback receives (element, index, array). Use map when you have a one-to-one transformation: every input element produces exactly one output element. It is the array equivalent of a mathematical function applied element-wise.
filter — Select
filter(predicate) keeps only the elements for which the predicate returns a truthy value. The result array may be shorter than the input. The callback receives (element, index, array). Use filter when you want a subset based on a condition — it is the declarative replacement for a manual loop with push.
reduce — Accumulate
reduce(fn, initialValue) walks the array left to right, carrying an accumulator that is updated by each step. The callback receives (accumulator, element, index, array). It is the most powerful of the three: map and filter can be implemented with reduce. Use it to sum, flatten, group, count, or build any single value from an array. Always pass an initial value to avoid the subtle behavior where the first element is used as the initial accumulator when one is omitted.
Chaining
Because each method returns a new array, you can chain them into a readable data pipeline: data.filter(...).map(...).reduce(...). Each step is a small, testable transformation. The trade-off is that chaining creates intermediate arrays; for very large datasets, a single reduce or a for loop may be more efficient. Optimize only when profiling shows a real bottleneck.
Composition Over Mutation
The functional style favors composing small pure functions over writing one big imperative loop. This scales better: each step is independent, testable, and reusable. The key discipline is to never mutate inside the callbacks — return new values, and let the methods build the result arrays.
Example
const orders = [
{ id: 1, customer: "Ada", total: 120, status: "shipped" },
{ id: 2, customer: "Alan", total: 85, status: "pending" },
{ id: 3, customer: "Ada", total: 200, status: "shipped" },
{ id: 4, customer: "Grace", total: 50, status: "cancelled" },
{ id: 5, customer: "Alan", total: 300, status: "shipped" },
];
// Pipeline: filter shipped → map to total → reduce to sum
const shippedRevenue = orders
.filter((o) => o.status === "shipped")
.map((o) => o.total)
.reduce((sum, total) => sum + total, 0);
console.log("Shipped revenue:", shippedRevenue); // 620
// reduce to group by customer
const byCustomer = orders.reduce((groups, order) => {
const key = order.customer;
(groups[key] ??= []).push(order);
return groups;
}, {});
console.log("By customer:", Object.keys(byCustomer));
// reduce to find the max total
const maxOrder = orders.reduce(
(max, o) => (o.total > max.total ? o : max),
orders[0]
);
console.log("Largest order:", maxOrder.id, maxOrder.total);
// map to transform shape, filter to drop cancelled
const summaries = orders
.filter((o) => o.status !== "cancelled")
.map((o) => ({ id: o.id, label: `${o.customer} — $${o.total}` }));
console.log("Summaries:", summaries);
// flatten with reduce
const nested = [[1, 2], [3, 4], [5]];
const flat = nested.reduce((acc, arr) => [...acc, ...arr], []);
console.log("Flat:", flat); // [1, 2, 3, 4, 5]
Shows a filter→map→reduce revenue pipeline, grouping by customer with reduce, finding the max with reduce, transforming shape with map+filter, and flattening nested arrays with reduce.
Try it
- JSON Formatter
Format the arrays of objects you transform with map/filter/reduce.
- CSV to JSON
Convert CSV to arrays of objects, then process them functionally.
Common mistakes
The mistake
Forgetting the initial value in reduce
The fix
Without an initial value, reduce uses the first element as the accumulator and skips it. This causes bugs when the array is empty or the accumulator type differs from the element type. Always pass an explicit initial value as the second argument.
The mistake
Mutating the original array or its elements inside a map/filter callback
The fix
map, filter, and reduce are meant to be pure. Mutating elements or the source array breaks immutability and causes subtle bugs. Return new objects/arrays from the callback and never call push or splice on the input.
Related Resources
Related Snippets
- Array Map / Filter / Reduce
Complete reference of functional array methods with real examples.
Related Cheatsheets
- JavaScript Cheatsheet
map, filter, reduce signatures and chaining patterns.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.