map, filter, reduce

map

Example

map creates a new array by transforming every element:

const prices = [100, 250, 400];
const withTax = prices.map(p => p * 1.18);
console.log(withTax);
const names = ["asha", "vikram"].map(n => n[0].toUpperCase() + n.slice(1));
console.log(names);

Output

[ 118, 295, 472 ]
[ 'Asha', 'Vikram' ]

filter

Example

filter keeps only the elements for which the callback returns true:

const students = [
  { name: "Asha", marks: 92 },
  { name: "Vikram", marks: 38 },
  { name: "Neha", marks: 75 },
];
const passed = students.filter(s => s.marks >= 40);
console.log(passed.map(s => s.name));

Output

[ 'Asha', 'Neha' ]

reduce

Example

reduce combines all elements into one value, carrying an accumulator:

const cart = [{ item: "Pen", price: 10, qty: 3 }, { item: "Book", price: 250, qty: 1 }];
const total = cart.reduce((sum, line) => sum + line.price * line.qty, 0);
console.log(total);
const countByLetter = ["apple", "avocado", "banana"].reduce((acc, w) => {
  acc[w[0]] = (acc[w[0]] ?? 0) + 1;
  return acc;
}, {});
console.log(countByLetter);

Output

280
{ a: 2, b: 1 }

forEach and Chaining

Example

Methods that return arrays can be chained into readable pipelines:

const orders = [120, 45, 800, 300, 20];
const bigOrdersTotal = orders
  .filter(o => o >= 100)
  .map(o => o * 0.9)          // 10% discount
  .reduce((a, b) => a + b, 0);
console.log(bigOrdersTotal);
orders.forEach((o, i) => console.log(i, o));

Output

1098
0 120
1 45
2 800
3 300
4 20