Tutorials JavaScript map, filter, reduce
Ch 32 / 78
Chapter 32 Intermediate 10 min read JavaScript

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.

What you'll learn
How map transforms every array element into a new array
How filter creates a subset by keeping elements that pass a test
How reduce folds an array into a single accumulated value
Chaining map → filter → reduce in a single pipeline
When to use each method vs a for loop
Real-world data transformation patterns and recipes

The 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:

.map()
Transform Every Element
Calls the callback on every element and returns a new array of the same length filled with the callback's return values.
Returns: new array (same length, transformed values)
.filter()
Keep Matching Elements
Calls the callback on every element and returns a new array containing only elements where the callback returned true.
Returns: new array (shorter or equal length, same values)
.reduce()
Accumulate Into One Value
Calls the callback on every element, passing along an accumulator value. Returns the final accumulated result — a number, string, object, or array.
Returns: single value (any type)

They chain naturally — output of one becomes the input of the next:

[1, 2, 3, 4, 5]
Original Array
→
.map(x ⇒ x²)
Transform
→
.filter(x > 5)
Subset
→
.reduce(sum)
Accumulate
→
60
Final Result

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:

array.map((element, index, array) => returnValue)
element — current item being processed index — position (0-based), optional array — the original array, optional returnValue — what this element becomes in the new array
map — how it works
1 Creates empty result array of same length
2 Calls callback for every element (left → right)
3 Stores return value at same index in result array
4 Returns new array — original is unchanged
Key rules
! Always return a value — forgetting returns undefined
! Never mutate the original array inside the callback
! Result length always equals input length
! Use forEach for side-effects; map for transformations
JavaScript — Array.map()
// ── 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)
Watch Out
When using an arrow function with curly 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:

array.filter((element, index, array) => boolean)
element — current item being tested index — position, optional boolean — truthy keeps the element; falsy drops it Result length ≤ input length (never longer)
JavaScript — Array.filter()
// ── 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"]
Tip
Passing 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:

array.reduce((accumulator, currentValue, index) => newAccumulator, initialValue)
accumulator — running total / result carried between iterations currentValue — element being processed this iteration index — current position, optional initialValue — starting value of the accumulator (strongly recommended)
JavaScript — Array.reduce()
// ── 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
Always provide initialValue
Without an 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:

JavaScript — Chaining map → filter → reduce
// ── 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:

Add Tax to Prices
Apply a formula to every price in a product list to generate a new list with tax included.
.map()
Search / Filter Results
Filter a list of items by search query, category, or status — returns only matching records.
.filter()
Cart Total
Sum all item prices in a shopping cart, including quantities, to compute the final total.
.reduce()
Extract IDs / Names
Pull a single property from an array of objects — e.g., map an array of users to just their IDs.
.map()
Active Users Only
Remove inactive, banned, or expired accounts from a list before displaying or processing.
.filter()
Group by Category
Use reduce to group an array of objects by a shared property — e.g., products by department.
.reduce()
Remove Nulls / Falsy
Clean a dataset by removing empty strings, null, and undefined values in a single pass.
.filter(Boolean)
Full Pipeline
Chain filter → map → reduce to clean, transform, and aggregate data in one readable expression.
.chain()
⚡
Free Resource
Download our JavaScript Cheat Sheet
map, filter, reduce & array patterns — all on one page.
Get Sheet

Try It — Live Editor

Experiment with map, filter, and reduce below. Try chaining them together or modifying the data to see the output change.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are everyday map/filter/reduce utilities you'll reach for constantly in real JavaScript projects:

JavaScript — Recipes
// ── 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, []);
Quick Check
What does [1, 2, 3].map(n => n * 2) return?
Quick Check
Which method would you use to calculate the total price of all items in a shopping cart array?
Quick Check
What is the result of [5, 12, 3, 8].filter(n => n > 6)?
Chapter Summary
  • map() transforms every element and returns a new array of the same length. Always return a value from the callback, or you'll get undefined entries.
  • 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 initialValue to 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 map and filter can be implemented using reduce alone.
  • For simple side-effects (like logging), prefer forEach. For transformations and data processing, use map, filter, and reduce.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel