re: Explain REDUCE Like I'm Five VIEW POST


I use it when I want to do something on an array and get a single value in return.

const totalCost = foodItems.reduce((total,item) => total + item.cost, 0)

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

const coolObj = coolArr.reduce((obj,item) => something something, {})

(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 😶


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 >.>

code of conduct - report abuse