Module 22: Loops and Algorithms

Lesson 2 of 5 · 15–25 minutes

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

const names = products.map(p => p.name);
const lowStock = products.filter(p => p.stock < 5);
const totalValue = products.reduce((sum, p) => sum + p.price * p.stock, 0);

sum carries the running total; 0 is where it starts.

🖱️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.

← PreviousWhat an algorithm is
ProLearners Assist