Labs ICT
Pro Login

Map, Filter & Reduce

Map, Filter, and Reduce

These three array methods are the backbone of functional programming in JavaScript. They let you transform, filter, and aggregate data without mutating the original array.

const numbers = [1, 2, 3, 4, 5];

// Map — transform each element
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// Filter — keep elements that pass a test
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

// Reduce — combine into a single value
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15

How Map Works

map() creates a new array by calling a function on every element. The function receives the element, its index, and the original array. The returned value becomes the new element.

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
];

const names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob"]

How Filter Works

filter() keeps only the elements where the callback returns true. It creates a new array without modifying the original.

const products = [
  { name: "Laptop", price: 999, inStock: true },
  { name: "Phone", price: 699, inStock: false },
  { name: "Tablet", price: 499, inStock: true },
];

const available = products.filter(p => p.inStock);
console.log(available.length); // 2

Chaining Them Together

The real power comes from chaining these methods. You can transform, filter, and aggregate in a clean, readable pipeline.

const orders = [
  { item: "Shirt", price: 30, quantity: 2 },
  { item: "Pants", price: 50, quantity: 1 },
  { item: "Socks", price: 5, quantity: 10 },
];

const totalRevenue = orders
  .map(order => order.price * order.quantity)
  .filter(amount => amount > 50)
  .reduce((sum, amount) => sum + amount, 0);

console.log(totalRevenue); // 160 (60 + 50 + 50)
Try it Yourself →

Summary

Map transforms, filter selects, and reduce accumulates. Master these three and you'll write cleaner, more declarative JavaScript code.