Mastering map, filter, and reduce in JavaScript
JavaScript provides powerful array methods map(), filter(), and reduce() to simplify data transformations, improve code readability, and eliminate unnecessary loops.
Understanding and leveraging these functions will significantly enhance your JavaScript coding skills.
Why use map , filter and reduce ?
These functions allow you to manipulate arrays efficiently without the need for explicit loops, resulting in cleaner, more readable, and more maintainable code.
1. map()
Purpose : map()
creates a new array by applying a function to each element of the original array.
When to Use ? : Use map()
when you need to transform or modify each element in an array.
Syntax
const newArray = array.map(callback(element, index, array));
Example
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map((num) => num * num);
console.log(squares); // Output: [1, 4, 9, 16, 25]
2. filter()
Purpose: filter()
creates a new array containing only elements that satisfy a given condition.
When to Use? : Use filter()
when you need to filter out elements based on a condition.
Syntax
const newArray = array.filter(callback(element, index, array));
Example
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
3. reduce()
Purpose: reduce()
accumulates array elements into a single value.
When to Use? : Use reduce()
when you need to aggregate data (e.g., sum, product, object transformation).
Syntax
const result = array.reduce(
callback(accumulator, currentValue, index, array),
initialValue
);
Example
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, num) => accumulator + num, 0);
console.log(sum); // Output: 15
Real-World Examples
1. Converting Product Prices (map()
)
const pricesInUSD = [10, 20, 30, 40];
const pricesInINR = pricesInUSD.map((price) => price * 80);
console.log(pricesInINR); // Output: [800, 1600, 2400, 3200]
2. Filtering Eligible Voters (filter()
)
const people = [
{ name: "Alice", age: 17 },
{ name: "Bob", age: 22 },
{ name: "Charlie", age: 15 },
{ name: "Diana", age: 18 },
];
const eligibleVoters = people.filter((person) => person.age >= 18);
console.log(eligibleVoters);
3. Calculating Total Order Value (reduce()
)
const cart = [
{ product: "Shoes", price: 50, quantity: 2 },
{ product: "T-shirt", price: 20, quantity: 3 },
{ product: "Jeans", price: 40, quantity: 1 },
];
const totalCost = cart.reduce((total, item) => total + item.price * item.quantity, 0);
console.log(totalCost); // Output: 200
Performance Considerations
map()
,filter()
, andreduce()
create new arrays, which may increase memory usage compared to modifying an existing array.For large datasets, traditional loops (
for
,while
) may perform better in terms of execution speed.
Error Handling
reduce()
without aninitialValue
can lead to errors when used on an empty array.Always ensure callbacks handle unexpected values to prevent runtime errors.
Example: Handling Empty Arrays in reduce()
const numbers = [];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 0 (safe default value)
Method Chaining: Combining map()
, filter()
, and reduce()
Using these methods together can create concise and powerful data transformations.
Example: Calculating Total Cost After Filtering Expensive Items
const products = [
{ name: "Laptop", price: 1000 },
{ name: "Mouse", price: 20 },
{ name: "Keyboard", price: 50 },
];
const totalCost = products
.filter(product => product.price > 30) // Keep only expensive items
.map(product => product.price * 1.1) // Apply 10% tax
.reduce((sum, price) => sum + price, 0);
console.log(totalCost);
Conclusion Table
Feature | map | filter | reduce | Traditional Loop |
Purpose | Transform elements | Filter elements | Aggregate data | Manual iteration, control flow |
Returns | New array of same length | New array of filtered elements | Single value | New array (using push ), manual accumulation |
Chaining Support | Yes | Yes | Yes | No |
Immutability | Yes | Yes | Yes | No (unless you manually copy data) |