The reduce method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of array and the return value of the function is stored in an accumulator.
Syntax
array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue);
Use cases of reduce in real scenarios:
1. Calculating Totals
const products = [
{ name: "Cactus", price: 30 },
{ name: "Pot", price: 20 },
{ name: "Glass", price: 10 }
];
const totalPriceReduce = products.reduce((sum, product) => sum + product.price, 0);
console.log("Total price:", totalPriceReduce); // Output: Total price: 60
2. Finding Maximum Value
const prices = [30, 20, 10];
const maxPriceReduce = prices.reduce((max, price) => Math.max(max, price), -Infinity);
console.log("Max price:", maxPriceReduce); // Output: Max price: 30
3. Removing Duplicates
const prices = [30, 20, 10, 20]
let newPrices = prices.reduce(function (accumulator, curValue) {
if(accumulator.indexOf(curValue) === -1) {
accumulator.push(curValue)
}
return accumulator
}, [])
console.log(newPrices); // Output: 30, 20, 10