JavaScript’s map(), filter(), and reduce() are essential tools for working with arrays, especially when dealing with arrays of objects. They let you write clean, functional code for transforming, filtering, and aggregating data. Here’s how you can use them effectively:
1. map()
– Transforming Data
The map()
method is perfect for creating new arrays by transforming each element.
📌 Use Case: Extracting or reformatting object properties.
Examples:
const products = [
{ name: 'Laptop', price: 1000 },
{ name: 'Phone', price: 500 },
{ name: 'Tablet', price: 700 },
];
// Example 1: Extract product names
const productNames = products.map(product => product.name);
console.log(productNames); // ['Laptop', 'Phone', 'Tablet']
// Example 2: Apply a discount to all prices
const discountedProducts = products.map(product => ({
...product,
price: product.price * 0.9,
}));
console.log(discountedProducts);
// [
// { name: 'Laptop', price: 900 },
// { name: 'Phone', price: 450 },
// { name: 'Tablet', price: 630 }
// ]
2. filter()
– Picking the Right Data
Use filter()
to create a subset of data based on a condition.
📌 Use Case: Filtering objects based on their properties.
Examples:
const employees = [
{ name: 'Alice', role: 'Developer' },
{ name: 'Bob', role: 'Designer' },
{ name: 'Charlie', role: 'Developer' },
];
// Example 1: Filter developers
const developers = employees.filter(employee => employee.role === 'Developer');
console.log(developers);
// [
// { name: 'Alice', role: 'Developer' },
// { name: 'Charlie', role: 'Developer' }
// ]
// Example 2: Filter employees whose names start with 'A'
const namesStartingWithA = employees.filter(employee => employee.name.startsWith('A'));
console.log(namesStartingWithA);
// [{ name: 'Alice', role: 'Developer' }]
3. reduce()
– Combining Data
The reduce()
method aggregates data from an array into a single value or object.
📌 Use Case: Summing values or building new structures.
Examples:
const orders = [
{ id: 1, amount: 100 },
{ id: 2, amount: 200 },
{ id: 3, amount: 300 },
];
// Example 1: Calculate the total amount
const totalAmount = orders.reduce((total, order) => total + order.amount, 0);
console.log(totalAmount); // 600
// Example 2: Group orders by amount threshold
const groupedOrders = orders.reduce((groups, order) => {
const category = order.amount > 150 ? 'High' : 'Low';
groups[category] = groups[category] || [];
groups[category].push(order);
return groups;
}, {});
console.log(groupedOrders);
// {
// Low: [{ id: 1, amount: 100 }],
// High: [{ id: 2, amount: 200 }, { id: 3, amount: 300 }]
// }
Chaining Example
You can combine these methods to process data step by step.
const users = [
{ name: 'Alice', age: 25, isActive: true },
{ name: 'Bob', age: 30, isActive: false },
{ name: 'Charlie', age: 35, isActive: true },
];
// Get active users, double their age, and calculate the total
const totalAge = users
.filter(user => user.isActive) // Active users
.map(user => ({ ...user, age: user.age * 2 })) // Double their age
.reduce((sum, user) => sum + user.age, 0); // Sum their ages
console.log(totalAge); // 120 (Alice: 50, Charlie: 70)
Why Use These Methods?
- Efficiency: Perform operations without manual loops.
- Readability: Your code is easier to understand.
- Immutability: They don’t modify the original array.
Mastering these methods with arrays of objects will supercharge your JavaScript skills! 🚀 Let me know your favorite use case in the comments! 👇
Top comments (0)