Here I want to calculate totalCost (a single value)
so in this we are returning total + item.cost in every iteration, Whatever you return gets stored in the first parameter (total in this case) and you can use this stored value in next iterations.
Next parameter inside the callback function (item in this case) is the one value from an array which changes in every iteration
the 2nd parameter in the reduce function (0 in this case) is the initial value of total.
so lets say you want an object in return in that case you can do
It's not great, but it goes a lot more smoothly when you turn off autocorrect. All of the operating systems have native swipe-to-type now, too, which obviates most of the unpleasantness. At least, when you're not on one of those gargantuan "Plus" phones >.>
I use it when I want to do something on an array and get a single value in return.
Here I want to calculate totalCost (a single value)
so in this we are returning
total + item.cost
in every iteration, Whatever you return gets stored in the first parameter (total
in this case) and you can use this stored value in next iterations.Next parameter inside the callback function (
item
in this case) is the one value from an array which changes in every iterationthe 2nd parameter in the reduce function (
0
in this case) is the initial value oftotal
.so lets say you want an object in return in that case you can do
(Sorry I'm on my phone right now I'll try to explain better in the morning.)
I'm always doing these things from my phone 😶
haha I hate typing from phone
It's not great, but it goes a lot more smoothly when you turn off autocorrect. All of the operating systems have native swipe-to-type now, too, which obviates most of the unpleasantness. At least, when you're not on one of those gargantuan "Plus" phones >.>
I will suggest to try out Array Cardio chapter from JavaScript 30 :D