Module 22: Loops and Algorithms
Transforming data with map, filter and reduce
🏠The everyday picture
A sorting line in a mango orchard: one station washes every mango (map), the next throws out the bruised ones (filter), and the last weighs the whole crate (reduce).
📘What it really is
mapmakes a new array by changing each item:
const names = products.map(p => p.name);
filtermakes a new array of only the items that pass a test:
const lowStock = products.filter(p => p.stock < 5);
reducecombines all items into one value, such as a total:
const totalValue = products.reduce((sum, p) => sum + p.price * p.stock, 0);
sum carries the running total; 0 is where it starts.
- They can be chained:
products.filter(p => p.category === "Pens").map(p => p.name). - None of them change the original array.
- A plain
for...ofloop can do all of this too. Use whichever you can read most easily; AI code uses these methods a lot, so learn to read them.
🖱️Try it
Using your products, produce: a list of all names; only the products under ₹50; the total value of all stock
(your pseudocode from Lesson 1); and the names of products in one category, using a chain. Write each with a
for...of loop as well and check that the results match.
✅Quick check
You want a list of prices with 18% GST added. map, filter or reduce?
Show the answer
map, because each item becomes a new value and the list stays the same length.
What's the 0 for in reduce((sum, p) => sum + p.price, 0)?
Show the answer
It's the starting value of sum. Without it, an empty list would cause an error.
