Array.prototype.reduce()
Start with a list of value, and iterate through them to compute a single value
// Simple Example
const nums = [1, 2, 3];
const add = (a, b) => a + b;
const result = nums.reduce(add)
const orders = [
{ id: '🥯', total: 11.00 },
{ id: '🍖', total: 23.00 },
{ id: '🥗', total: 7.00 }
];
// Using For loop
let total = 0;
for (const order of orders) {
total += order.total;
}
// Using Reduce - reduceRight to start from the end
let total = orders.reduce(
// acc contains the value last returned from this function
// currentOrder contains the current value in the loop
(acc, currentOrder) => {
return acc + currentOrder.total;
},
// Default Value to start with
0
);