map, filter, reduce
Three of the most powerful array methods in JavaScript —
map transforms every element,
filter keeps only elements that pass a test, and
reduce accumulates all elements into a single value.
Mastering these three methods unlocks clean, declarative, functional-style data processing.
map transforms every array element
into a new arrayfilter creates a subset by keeping
elements that pass a testreduce folds an array into a
single accumulated valueThe Three Iteration Methods
These three methods are higher-order functions —
each accepts a callback that is called once per element.
Unlike a for loop, they don't mutate the original
array and express what you want rather than how to loop:
true.
They chain naturally — output of one becomes the input of the next:
Array.map()
map() creates a new
array by calling your callback on every element. The callback receives
(element, index, array) and its return value
becomes the corresponding element in the new array. The original array is never modified:
undefined
forEach for side-effects; map
for transformations
// ── Basic transformation ───────────────────────────────────── const nums = [1, 2, 3, 4, 5]; const squared = nums.map(n => n * n); console.log(squared); // [1, 4, 9, 16, 25] console.log(nums); // [1, 2, 3, 4, 5] ← original untouched // ── Using index parameter ──────────────────────────────────── const indexed = ["a", "b", "c"].map((val, i) => `${i}: ${val}`); console.log(indexed); // ["0: a", "1: b", "2: c"] // ── Transforming objects ───────────────────────────────────── const products = [ { name: "Laptop", price: 800 }, { name: "Phone", price: 400 }, { name: "Tablet", price: 250 }, ]; const withTax = products.map(p => ({ ...p, priceWithTax: (p.price * 1.18).toFixed(2) })); // [{ name: "Laptop", price: 800, priceWithTax: "944.00" }, ...] // ── Extract a property from array of objects ───────────────── const names = products.map(p => p.name); console.log(names); // ["Laptop", "Phone", "Tablet"] // ── Common mistake: forgetting to return ───────────────────── const broken = nums.map(n => { n * n }); // ❌ missing return console.log(broken); // [undefined, undefined, undefined, ...] const fixed = nums.map(n => { return n * n; }); // ✅ explicit return const fixedArrow = nums.map(n => n * n); // ✅ implicit return (no braces)
{ }, you must
write an explicit return. Without it, the callback returns
undefined and your mapped array will be full of
undefined values. Use the concise arrow form n => n * n
when the body is a single expression.
Array.filter()
filter() creates a new
array containing only the elements for which the callback returns a
truthy value. Elements where the callback returns
false (or any falsy value) are excluded.
The original array is unchanged:
// ── Basic filtering ────────────────────────────────────────── const scores = [45, 72, 88, 55, 91, 38, 66]; const passed = scores.filter(s => s >= 60); console.log(passed); // [72, 88, 91, 66] // ── Filter even numbers ────────────────────────────────────── const evens = [1, 2, 3, 4, 5, 6].filter(n => n % 2 === 0); console.log(evens); // [2, 4, 6] // ── Remove falsy values ────────────────────────────────────── const dirty = [0, "hello", "", null, 42, undefined, false, "world"]; const clean = dirty.filter(Boolean); // passes Boolean as callback console.log(clean); // ["hello", 42, "world"] // ── Filter objects by property ─────────────────────────────── const users = [ { name: "Alice", active: true, age: 28 }, { name: "Bob", active: false, age: 34 }, { name: "Carol", active: true, age: 22 }, { name: "Dave", active: false, age: 41 }, ]; const activeUsers = users.filter(u => u.active); // [{ name: "Alice", ... }, { name: "Carol", ... }] const adults = users.filter(u => u.active && u.age >= 25); // [{ name: "Alice", ... }] — active AND age >= 25 // ── Remove duplicates (with Set) ───────────────────────────── const tags = ["js", "css", "js", "html", "css"]; const unique = tags.filter((t, i, arr) => arr.indexOf(t) === i); console.log(unique); // ["js", "css", "html"]
Boolean directly as the callback — .filter(Boolean) —
is a clean shorthand for removing all falsy values (0, "",
null, undefined, NaN, false)
from an array in one expression.
Array.reduce()
reduce() is the most powerful
— and most misunderstood — of the three. It calls the callback on each element,
passing along an accumulator that carries the running result.
The final value of the accumulator is returned. You can reduce to a number,
string, object, or even an array:
// ── Sum of numbers ─────────────────────────────────────────── const nums = [10, 20, 30, 40]; const total = nums.reduce((acc, n) => acc + n, 0); console.log(total); // 100 // Step-by-step: 0+10=10 → 10+20=30 → 30+30=60 → 60+40=100 // ── Max value ──────────────────────────────────────────────── const max = nums.reduce((acc, n) => n > acc ? n : acc, -Infinity); console.log(max); // 40 // ── Count occurrences ──────────────────────────────────────── const fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"]; const count = fruits.reduce((acc, fruit) => { acc[fruit] = (acc[fruit] || 0) + 1; return acc; }, {}); console.log(count); // { apple: 3, banana: 2, cherry: 1 } // ── Flatten an array of arrays ─────────────────────────────── const nested = [[1, 2], [3, 4], [5, 6]]; const flat = nested.reduce((acc, arr) => acc.concat(arr), []); console.log(flat); // [1, 2, 3, 4, 5, 6] // ── Group objects by property ──────────────────────────────── const people = [ { name: "Alice", dept: "Engineering" }, { name: "Bob", dept: "Marketing" }, { name: "Carol", dept: "Engineering" }, ]; const byDept = people.reduce((acc, p) => { (acc[p.dept] = acc[p.dept] || []).push(p.name); return acc; }, {}); // { Engineering: ["Alice", "Carol"], Marketing: ["Bob"] } // ── Always provide the initial value ───────────────────────── [].reduce((acc, n) => acc + n); // ❌ TypeError on empty array [].reduce((acc, n) => acc + n, 0); // ✅ returns 0 safely
initialValue, reduce() uses the first element as
the accumulator and starts from index 1. On an empty array with no
initialValue, it throws a TypeError. Always pass an explicit
starting value — 0 for sums, [] for arrays,
{} for objects.
Chaining map, filter & reduce
Because map and
filter both return arrays, they can be
chained together — and the chain can end with
reduce to collapse everything into a single value.
This is the foundation of functional, declarative data processing in JavaScript:
// ── Chain: sum of squares of odd numbers ─────────────────────
const result = [1, 2, 3, 4, 5]
.filter(n => n % 2 !== 0) // keep odds: [1, 3, 5]
.map(n => n * n) // square them: [1, 9, 25]
.reduce((acc, n) => acc + n, 0); // sum: 35
console.log(result); // 35
// ── Real-world: active user total spend ─────────────────────
const orders = [
{ user: "Alice", active: true, amount: 120 },
{ user: "Bob", active: false, amount: 340 },
{ user: "Carol", active: true, amount: 89 },
{ user: "Dave", active: true, amount: 210 },
];
const activeTotal = orders
.filter(o => o.active) // only active users
.map(o => o.amount) // extract amounts: [120, 89, 210]
.reduce((sum, a) => sum + a, 0); // total: 419
console.log(activeTotal); // 419
// ── Build a summary object in one pipeline ───────────────────
const summary = orders
.filter(o => o.active)
.reduce((acc, o) => ({
count: acc.count + 1,
total: acc.total + o.amount,
avgStr: "" // placeholder, computed after
}), { count: 0, total: 0 });
summary.avg = (summary.total / summary.count).toFixed(2);
console.log(summary); // { count: 3, total: 419, avg: "139.67" }map vs filter vs reduce vs for
Choosing the right tool depends on what you want to produce. This table summarises the key differences:
| Feature | map | filter | reduce |
|---|---|---|---|
| Returns | New array | New array (subset) | Single value (any type) |
| Output length | Always same as input | ≤ input length | Not an array (usually) |
| Callback must return | The new element value | true / false (boolean-ish) | The new accumulator value |
| Mutates original? | Never | Never | Never (unless you do it) |
| Use when you want to… | Transform every element | Keep only some elements | Aggregate, group, fold |
| Equivalent for loop | Push result each iteration | Conditional push | Running total / object build |
Real-World Use Cases
These three methods cover the vast majority of real data transformation tasks you'll face in frontend and backend JavaScript:
Try It — Live Editor
Experiment with map,
filter, and reduce
below. Try chaining them together or modifying the data to see the output change.
Common Patterns & Recipes
These are everyday map/filter/reduce utilities you'll reach for constantly in real JavaScript projects:
// ── Unique values ──────────────────────────────────────────── const unique = arr => [...new Set(arr)]; unique([1, 2, 2, 3, 1]); // [1, 2, 3] // ── keyBy — turn array into lookup object ──────────────────── const keyBy = (arr, key) => arr.reduce((acc, item) => { acc[item[key]] = item; return acc; }, {}); keyBy(users, "id"); // { 1: {...}, 2: {...} } — O(1) lookup // ── pluck — extract one field from all objects ─────────────── const pluck = (arr, key) => arr.map(item => item[key]); pluck(users, "name"); // ["Alice", "Bob", "Carol"] // ── partition — split into two groups ─────────────────────── const partition = (arr, predicate) => arr.reduce(([pass, fail], item) => predicate(item) ? [[...pass, item], fail] : [pass, [...fail, item]], [[], []]); const [adults, minors] = partition(users, u => u.age >= 18); // ── Running total per item ─────────────────────────────────── const runningTotal = prices => prices.reduce((acc, p) => { acc.push((acc[acc.length - 1] || 0) + p); return acc; }, []); runningTotal([10, 20, 30]); // [10, 30, 60] // ── Implement map with reduce ───────────────────────────────── const myMap = (arr, fn) => arr.reduce((acc, x) => [...acc, fn(x)], []); // ── Implement filter with reduce ────────────────────────────── const myFilter = (arr, fn) => arr.reduce((acc, x) => fn(x) ? [...acc, x] : acc, []);
[1, 2, 3].map(n => n * 2) return?[5, 12, 3, 8].filter(n => n > 6)?
- map() transforms every element and returns a new array of the same
length. Always return a value from the callback, or you'll get
undefinedentries. - filter() keeps only elements where the callback returns truthy, producing a new array that is shorter than or equal to the original.
- reduce() folds the entire array into a single accumulated value. Always
provide an
initialValueto avoid errors on empty arrays. - None of these methods mutate the original array — they always return a new value, making code predictable and easy to test.
- Chaining —
.filter().map().reduce()— is the backbone of functional, declarative data pipelines in JavaScript. - Use
.filter(Boolean)as a concise shorthand to remove all falsy values from an array in one step. - reduce() is universal — both
mapandfiltercan be implemented usingreducealone. - For simple side-effects (like logging), prefer
forEach. For transformations and data processing, usemap,filter, andreduce.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.