I'm new to coding, so this might be a simple question but one that I can't understand. I have an array of all the best pies each with their own price:
pieArr = [blueberry, strawberry, pumpkin, apple]
I want to create an array of objects that shows the total of the shopping cart depending on the price of the pie, and someone here on stack overflow recommended I use reduce.
This is what I have so far:
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;
},
[])};
What I want the end result to be is a new array of objects that keeps adding the new totals:
[{cartTotal:2.5},{cartTotal:4.5}]
The new array of objects get created, but the total doesn't get added up, so it ends up with total being 0 both times:
[{cartTotal: 0},{cartTotal: 0}]
What am I doing wrong?
const total = 0;Er,const, you sure? Alsoconst total = total + 2.5;is invalid syntax, the code shouldn't run in the first place, I'd think? (Also, you probably want toreturn totalPricewhen the firstifcondition is fulfilled as well)const total = total + 2.5;you’re declaring and reading your variable at the same time. Note that the outerconst total = 0;is overshadowed here. Did you really mean toconst-declare this? Where’s the}for theelse if? Are you sure, you’re returning a value in both cases?constif you are changing that variable. And lettotalbe defined outsidereduceoperation. This way total will not be initializing after one iteration of reduce operation.