Process lists of data
Much of real work consists of transforming lists of data:
sales, users, products... The map, filter and reduce trio is the
perfect tool.
const sales = [
{ product: "keyboard", price: 25, quantity: 3 },
{ product: "mouse", price: 15, quantity: 5 },
{ product: "monitor", price: 150, quantity: 1 },
];
// 1. map: compute the total of each line
const totals = sales.map((s) => s.price * s.quantity);
// 2. filter: only expensive sales
const expensive = sales.filter((s) => s.price > 20);
// 3. reduce: total revenue
const totalRevenue = sales.reduce(
(acc, s) => acc + s.price * s.quantity,
0
);
console.log(totals); // [75, 75, 150]
console.log(totalRevenue); // 300
Chaining transformations
The real power appears when you chain these methods:
const revenueFromExpensiveProducts = sales
.filter((s) => s.price > 20)
.map((s) => s.price * s.quantity)
.reduce((acc, total) => acc + total, 0);
Read the flow from top to bottom: filter, transform and aggregate. It is declarative and very readable.
Examples
Group and summarize data
const users = [
{ name: "Ana", active: true },
{ name: "Luis", active: false },
{ name: "Eva", active: true },
];
const active = users.filter((u) => u.active).map((u) => u.name);
console.log("Active users:", active);