I am facing an issue with summing the "amount" property of objects in an array using reduce. When I tried to add them up, it kept returning undefined even though logging the values individually worked fine.
let items = [
{ id: 0, name: "Food", amount: 30000 },
{ id: 1, name: "Insurance", amount: 25000 },
{ id: 2, name: "Rent", amount: 50000 }
]
let total = items.reduce((a, b) => {
console.log(b.amount); // 30000 (first loop)
a + b.amount; // undefined
}, 0);
console.log(total);
In order to fix this issue and get the expected result of summing all amounts, I need to remember to include a return statement inside the reduce function.
let items = [
{ id: 0, name: "Food", amount: 30000 },
{ id: 1, name: "Insurance", amount: 25000 },
{ id: 2, name: "Rent", amount: 50000 }
]
let total = items.reduce((a, b) => {
console.log(b.amount); // 30000 (first loop)
return a + b.amount; // 105000 OK
}, 0);
console.log(total);