I am a beginner in coding, so I apologize if this question seems basic. I am working with an array that contains different types of pies along with their prices:
pieArr = [blueberry, strawberry, pumpkin, apple]
My goal is to create an array of objects representing the total cost of the shopping cart based on the pie prices. A helpful user on stack overflow suggested using the reduce method for this task.
Here is my current code snippet:
var total = 0;
const totalArr = pieArr.reduce((totalPrice, pie) => {
if ( pie === "blueberry") {
total += 2.5;
totalPrice.push({["cartTotal"]:total});
return totalPrice;
}
else if (pie === "apple") {
total += 2;
totalPrice.push({["cartTotal"]:total});
return totalPrice;
},
[])};
My desired outcome is a new array of objects that continuously accumulates the total cost:
[{cartTotal:2.5},{cartTotal:4.5}]
Although the new array of objects is created, the total amount is not being properly calculated, resulting in both totals being 0:
[{cartTotal: 0},{cartTotal: 0}]
I am struggling to figure out what I am doing wrong. Any guidance would be appreciated.