SyntaxPilot
Courses/JavaScript/Lesson 11
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript · Lesson 11 of 40

map, filter and reduce

queued

These are the notes for JavaScript episode 11. You will learn why hand-written loops hide bugs, higher-order functions, map (change every item), the index argument, the { }-with-no-return trap, forEach vs map, filter (keep some items), filtering arrays of objects, reduce (combine into one value) traced step by step, TypeError: Reduce of empty array with no initial value, chaining, find, some and every, the map(parseInt) trap, and a mini project: a daily sales report. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

The problem: three loops, one bug

End of the day at Ravi's stall. The day's bills are an array of prices, and there are three jobs: add GST to every bill, list only the big orders (over Rs 100), and get the day's total. Three jobs, three loops:

const prices = [30, 160, 60, 250];
const withGst = [];
for (let i = 0; i < prices.length; i++) {
  withGst.push(prices[i] * 1.12);
}
const big = [];
for (let i = 0; i < prices.length; i++) {
  if (prices[i] > 100) big.push(prices[i]);
}
let total = 0;
for (let i = 0; i <= prices.length; i++) {
  total += prices[i];
}
console.log(withGst);
console.log(big);
console.log(total);
[ 33.6, 179.20000000000002, 67.2, 280 ]
[ 160, 250 ]
NaN

The third loop uses <= instead of <. It runs one step too far, reads prices[4] (which is undefined), and 500 + undefined is NaN.

Why it failed: each loop is five lines, but only one line is the real job. The rest is the same skeleton every time: an empty array, a counter, a condition, push. Write the skeleton a hundred times and one day you'll get it wrong. What if the loop was written once, and we only handed over the one line that matters, as a function?

A conveyor belt: the three machines

A factory conveyor belt In JavaScript Result
A machine that changes every item (empty cup → filled cup) arr.map(fn) a new array, same length, every item changed
A gate that lets only some items through arr.filter(fn) a new array of the items where fn returns true
A cash box that adds everything into one total arr.reduce(fn, start) one value

In all three, the belt is the loop, already written for you. You hand over only the rule, as a function (a callback, episode 9). A function that takes or returns another function, like map, filter and reduce, is a higher-order function.

map: change every item

const prices = [30, 160, 60, 250];
const withGst = prices.map((p) => p * 1.12);
console.log(withGst);
console.log(prices);
const labels = prices.map((p, i) => `#${i + 1}: Rs ${p}`);
console.log(labels);
[ 33.6, 179.20000000000002, 67.2, 280 ]
[ 30, 160, 60, 250 ]
[ '#1: Rs 30', '#2: Rs 160', '#3: Rs 60', '#4: Rs 250' ]
  • map calls your function on every item and collects the return values into a new array of the same length.
  • The original array is not changed.
  • The callback also receives the index (and the whole array) as extra arguments: (item, index, array).
  • 179.20000000000002 is a floating-point rounding effect (episode 3); round with Math.round or toFixed when you print money.

Traps: { } with no return, and forEach

const prices = [30, 160, 60, 250];
const doubled = prices.map((p) => { p * 2; });
console.log(doubled);
const result = prices.forEach((p) => p * 2);
console.log(result);
[ undefined, undefined, undefined, undefined ]
undefined
  • Curly brackets switch off an arrow's implicit return (episode 9), so every item became undefined. Fix: (p) => p * 2 or { return p * 2; }.
  • forEach runs the function on each item but collects nothing: it always returns undefined. Use forEach only to do something (print, save); use map when you want a new array back.
map forEach
Returns a new array undefined
Use it to transform data do something for each item

filter: keep some items

const prices = [30, 160, 60, 250];
const big = prices.filter((p) => p > 100);
console.log(big);
const wrong = prices.map((p) => p > 100);
console.log(wrong);
const orders = [
  { name: "Asha", amount: 30, paid: true },
  { name: "Meena", amount: 160, paid: false },
  { name: "Ravi", amount: 250, paid: false },
];
const unpaid = orders.filter((o) => !o.paid);
console.log(unpaid.map((o) => o.name));
[ 160, 250 ]
[ false, true, false, true ]
[ 'Meena', 'Ravi' ]
  • filter keeps the items where the callback returns true (or a truthy value). The callback is often called a predicate: a function that answers yes or no.
  • Using map with the same test changes every item into true/false instead of choosing items. map changes, filter chooses.
  • filter returns a new array: the same length or shorter, maybe empty, never longer.
  • Filtering, then mapping to names, shows how these tools snap together.

reduce: combine into one value

prices.reduce((sum, p) => sum + p, 0)
               │    │                └── start value (what sum begins as)
               │    └── the current item
               └── the running total (the accumulator)

Whatever your function returns becomes the next accumulator. After the last item, the accumulator is the answer. Watch it step by step:

const prices = [30, 160, 60, 250];
const total = prices.reduce((sum, p) => {
  console.log(`sum=${sum}, p=${p} -> ${sum + p}`);
  return sum + p;
}, 0);
console.log(total);
sum=0, p=30 -> 30
sum=30, p=160 -> 190
sum=190, p=60 -> 250
sum=250, p=250 -> 500
500

No counter to get wrong: the total is right this time.

More reduce, and the empty-array crash

const prices = [30, 160, 60, 250];
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(total);
const biggest = prices.reduce((max, p) => (p > max ? p : max), prices[0]);
console.log(biggest);
const empty = [];
console.log(empty.reduce((sum, p) => sum + p, 0));
console.log(empty.reduce((sum, p) => sum + p));
500
250
0
TypeError: Reduce of empty array with no initial value
  • reduce isn't only for adding: any time many items become one answer (a max, a count, an object), it's reduce.
  • Without a start value, reduce uses the first item as the start. An empty array has no first item, so it throws TypeError: Reduce of empty array with no initial value. A day with no sales would crash the app. Always give reduce a start value.

Chaining, find, some, every

const prices = [30, 160, 60, 250];
const bill = prices
  .filter((p) => p > 50)
  .map((p) => p * 1.12)
  .reduce((sum, p) => sum + p, 0);
console.log(Math.round(bill));
console.log(prices.find((p) => p > 100));
console.log(prices.some((p) => p > 200), prices.every((p) => p > 50));
526
160
true false
  • Each method returns a new array, so the next one can work on it: chaining. Read it top to bottom like a recipe: keep bills over 50 → add GST → add up. (160 + 60 + 250 = 470; × 1.12 = 526.4 → 526.)
Method Question it answers Returns
find(fn) which is the first item that passes? that item, or undefined
some(fn) does any item pass? true / false
every(fn) do all items pass? true / false

The map(parseInt) trap

console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map(Number));
console.log(["1", "2", "3"].map((s) => parseInt(s)));
[ 1, NaN, NaN ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]

map calls the callback with (item, index, array). parseInt's second parameter is the radix (number base), so the calls are parseInt("1", 0) → 1, parseInt("2", 1) → NaN (base 1 doesn't exist), parseInt("3", 2) → NaN (3 isn't a binary digit). Number uses only one argument, so it works. When in doubt, wrap the call in an arrow so you decide exactly what gets passed.

Common mistakes (and what really happens)

You wrote What happens Why Fix
for (let i = 0; i <= a.length; i++) (no error) NaN reads one past the end reduce (or <)
a.map((p) => { p * 2; }) (no error) [ undefined, ... ] { } turns off the implicit return a.map((p) => p * 2)
const r = a.forEach(...) (no error) undefined forEach returns nothing use map
a.map((p) => p > 100) to pick items (no error) [ false, true, ... ] map changes, doesn't choose a.filter(...)
[].reduce((s, p) => s + p) TypeError: Reduce of empty array with no initial value no start value reduce(fn, 0)
["1", "2"].map(parseInt) (no error) [ 1, NaN ] the index is passed as the radix map((s) => parseInt(s))
find expecting an array (no error) one item or undefined find returns the first match use filter for all matches

Mini project: a daily sales report

const sales = [
  { item: "chai", qty: 3, price: 10 },
  { item: "samosa", qty: 2, price: 12 },
  { item: "chai", qty: 5, price: 10 },
  { item: "vada pav", qty: 4, price: 15 },
  { item: "samosa", qty: 1, price: 12 },
];
const lines = sales.map((s) => ({ item: s.item, cost: s.qty * s.price }));
const bigLines = lines.filter((l) => l.cost >= 30);
const revenue = lines.reduce((sum, l) => sum + l.cost, 0);
const perItem = sales.reduce((acc, s) => {
  acc[s.item] = (acc[s.item] || 0) + s.qty;
  return acc;
}, {});
console.log("Big lines:", bigLines.length);
console.log("Revenue: Rs", revenue);
console.log("Sold:", perItem);
const top = Object.entries(perItem).sort((a, b) => b[1] - a[1])[0];
console.log(`Best seller: ${top[0]} (${top[1]})`);
Big lines: 3
Revenue: Rs 176
Sold: { chai: 8, samosa: 3, 'vada pav': 4 }
Best seller: chai (8)
  • map turns each sale into a line with its cost. Wrapping the object in ( ) is needed so the arrow returns an object instead of starting a block.
  • filter keeps lines worth Rs 30 or more (30, 50, 60).
  • The first reduce adds the costs; the second starts from an empty object {} and counts quantities per item: acc[s.item] || 0 uses 0 the first time an item appears.
  • Object.entries turns the counts into [item, count] pairs; sort (episode 7) puts the highest count first.

Try adding the average bill.

Practice

  1. From [3, 8, 12, 5], keep the numbers over 4 and square them.
  2. Use reduce to find the shortest word in an array.
  3. Count the vowels in a word with split and reduce.
  4. Add the average bill to the sales report.
Solutions and hints
const squares = [3, 8, 12, 5].filter((n) => n > 4).map((n) => n * n);
console.log(squares);
const words = ["samosa", "chai", "jalebi", "poha"];
const shortest = words.reduce((best, w) => (w.length < best.length ? w : best), words[0]);
console.log(shortest);
const vowels = "javascript".split("").reduce((count, ch) => ("aeiou".includes(ch) ? count + 1 : count), 0);
console.log(vowels);
const bills = [30, 24, 50, 60, 12];
const average = bills.reduce((sum, b) => sum + b, 0) / bills.length;
console.log(`Average bill: Rs ${average.toFixed(2)}`);
[ 64, 144, 25 ]
chai
3
Average bill: Rs 35.20
  1. Filter first, then map: fewer items to square.
  2. Keep whichever word is shorter; < (not <=) keeps the first one on a tie ("chai" before "poha").
  3. split("") turns the word into letters (episode 4); the accumulator counts.
  4. The line costs from the project are 30, 24, 50, 60, 12: total 176, divided by 5.

Quick quiz

What does this print?

const r = [1, 2, 3, 4]
  .filter((n) => n % 2 === 0)
  .map((n) => n * 10)
  .reduce((s, n) => s + n, 0);
console.log(r);
  • A. 100
  • B. 60
  • C. 40
  • D. [20, 40]
Answer

B. filter keeps the even numbers [2, 4]; map makes [20, 40]; reduce adds them: 60.

Interview questions

  • What's the difference between map, filter and reduce?
  • What does map return? Does it change the original array?
  • What's the difference between map and forEach?
  • What are the arguments of the reduce callback? What is the accumulator?
  • Why should you always pass an initial value to reduce? What happens on an empty array without one?
  • What's the difference between find and filter? Between some and every?
  • Why does ["1", "2", "3"].map(parseInt) return [1, NaN, NaN]?
  • What is a higher-order function? Give three built-in examples.
  • How would you count occurrences of each item in an array?
  • Implement map yourself using a for loop.

Glossary

Term Meaning Example
Callback a function passed to another function, which calls it (p) => p * 1.12
Higher-order function a function that takes or returns a function map, filter, reduce
map a new array with every item changed; same length prices.map((p) => p * 2)
filter a new array of the items where the callback is true prices.filter((p) => p > 100)
Predicate a callback that answers yes or no (p) => p > 100
reduce combines all items into one value prices.reduce((s, p) => s + p, 0)
Accumulator reduce's running result sum
Initial (start) value what the accumulator starts as 0, {}
forEach runs a function on each item, returns undefined prices.forEach((p) => console.log(p))
Chaining calling methods one after another on the results .filter(...).map(...).reduce(...)
find the first item that passes, or undefined prices.find((p) => p > 100) → 160
some does any item pass? prices.some((p) => p > 200) → true
every do all items pass? prices.every((p) => p > 50) → false
Index an item's position, passed as the 2nd callback argument (p, i) => ...
Radix the number base for parseInt parseInt("11", 2) → 3
Object.entries an object's [key, value] pairs as an array Object.entries({ chai: 8 }) → [["chai", 8]]
Off-by-one error a loop that runs one time too many or too few i <= a.length
Immutable operation makes a new value instead of changing the old one map and filter leave the original alone

Summary

  • Hand-written loops repeat the same skeleton, and the skeleton is where bugs hide. Hand over the rule instead.
  • map changes every item (same length, new array); filter keeps the items where the test is true; reduce combines everything into one value.
  • Callbacks get (item, index, array). Wrap built-ins like parseInt in an arrow.
  • forEach returns undefined; an arrow with { } needs return.
  • Always give reduce a start value.
  • find, some and every answer "which one?", "any?" and "all?". Chain them like a recipe.

Next episode: destructuring, spread and rest. Unpack objects in one line, and copy arrays without changing the original.