Modern Array Iterators (map, filter, reduce)
Functional array methods are the core of modern JavaScript programming. They allow you to transform, filter, and summarize data with elegant, declarative code.
What is it?
Higher-order array methods accept a callback function to iterate over elements without writing manual `for` loops. • `.map()`: Transforms every element into a new array. • `.filter()`: Returns a subset of elements passing a condition. • `.reduce()`: Reduces an array into a single accumulated value (sum, tally, object).
Why is it used?
Declarative, immutable, and easy to chain. Essential for React, Vue, and modern frontend data pipelines.
Detailed Explanation
Syntax Structure
const transformed = arr.map(item => item * 2);
const filtered = arr.filter(item => item.isActive);
const total = arr.reduce((acc, item) => acc + item.price, 0);
Code Example
const courseCatalog = [
{ id: 1, title: "Advanced Python", category: "Software", price: 2500, active: true },
{ id: 2, title: "Data Analytics", category: "Data Science", price: 2500, active: true },
{ id: 3, title: "Advanced Excel", category: "Data Science", price: 2500, active: true },
{ id: 4, title: "Legacy Pascal", category: "Archived", price: 1000, active: false }
];
// 1. FILTER: Only active Software/Data Science courses
const activeCourses = courseCatalog.filter(c => c.active);
// 2. MAP: Extract just course titles formatted
const courseTitles = activeCourses.map(c => `• ${c.title} (₹${c.price})`);
console.log("Active Course Titles:");
courseTitles.forEach(t => console.log(t));
// 3. REDUCE: Calculate total revenue if a student buys all active courses
const totalCatalogValue = activeCourses.reduce((sum, course) => sum + course.price, 0);
console.log(`Total Value of Catalog: ₹${totalCatalogValue}`);
Explanation of the Code
Expected Output
Real-World Application
Used in React components to render UI cards (`courses.map(c => <CourseCard ... />)`), filter search results, and sum shopping cart totals.
Common Mistakes to Avoid
Quick Practice Challenge
Given `[12, 5, 8, 130, 44]`, filter for numbers greater than 10 and multiply each by 2.