The reduce() method of an array executes a reducer function on each element of the array and returns a single output value.
With each execution, that returned value is added to the previous returned value in a variable named the accumulator. An initial value like 0 can be supplied, but, if it is not, the first value of the array is used. The method returns the final value of the accumulator.
const numbers = [1, 2, 3, 4];
const initialValue = 0;
const sum = numbers.reduce((accumulator, element) =>
accumulator + element, initialValue
);
console.log(sum);
// 10
// a common, more-advanced example
// sum a property in an array of objects
const snacks = [
{ name: 'chips', price: 3.2 },
{ name: 'pop', price: 2.5 },
{ name: 'gum', price: 1.5 },
];
const totalPrice = snacks.reduce((accumulator, snack) =>
accumulator + snack.price, 0);
console.log(totalPrice);
// 7.2
// a common, more-advanced example
// reduce can be used to group arrays - initial value is an empty object
// but groupBy() is the newer way to do this
const products = [
{ name: 'apples', category: 'fruits' },
{ name: 'oranges', category: 'fruits' },
{ name: 'potatoes', category: 'vegetables' }
];
const productsByCategory = products.reduce((group, product) => {
const { category } = product;
group[category] = group[category] ?? [];
group[category].push(product);
return group;
}, {});
console.log(productsByCategory);
{
'fruits': [
{ name: 'apples', category: 'fruits' },
{ name: 'oranges', category: 'fruits' },
],
'vegetables': [
{ name: 'potatoes', category: 'vegetables' }
]
}