Reduce:
The reduce() function iterates over the elements of an array and accumulates a single result by applying a provided function against an accumulator and each element in the array.
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 15
Industry Scenario: Consider an e-commerce platform where you need to calculate the total price of items in a shopping cart. You have an array of objects representing each item with properties like price and quantity. You can use reduce() to sum up the total price:
{ name: ‘Shirt’, price: 20, quantity: 2 },
{ name: ‘Pants’, price: 30, quantity: 1 },
{ name: ‘Shoes’, price: 50, quantity: 1 }
];
const totalPrice = cartItems.reduce((total, item) => total + (item.price * item.quantity), 0);
console.log(totalPrice); // Output: 120
ForEach:
The forEach() function executes a provided function once for each array element.
numbers.forEach(number => console.log(number));
// Output:
// 1
// 2
// 3
// 4
// 5
Industry Scenario: Consider a scenario in a project management tool where you want to update the status of each task in a list. You can use forEach() to iterate through the array of tasks and update their status:
{ id: 1, name: ‘Task 1’, status: ‘Pending’ },
{ id: 2, name: ‘Task 2’, status: ‘InProgress’ },
{ id: 3, name: ‘Task 3’, status: ‘Pending’ }
];
tasks.forEach(task => {
if (/* condition for updating status */) {
task.status = ‘Completed’;
}
});
reduce()
{ name: ‘Shirt’, price: 20, quantity: 2 },
{ name: ‘Pants’, price: 30, quantity: 1 },
{ name: ‘Shoes’, price: 50, quantity: 1 }
];
const totalPrice = cartItems.reduce((total, item) => total + (item.price * item.quantity), 0);
console.log(totalPrice); // Output: 120