DEV Community

Discussion on: Explain REDUCE Like I'm Five

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

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)
Enter fullscreen mode Exit fullscreen mode

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, {})
Enter fullscreen mode Exit fullscreen mode

(Sorry I'm on my phone right now I'll try to explain better in the morning.)

Collapse
 
thepeoplesbourgeois profile image
Josh

I'm always doing these things from my phone 😶

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

haha I hate typing from phone

Thread Thread
 
thepeoplesbourgeois profile image
Josh

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

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻 • Edited

I will suggest to try out Array Cardio chapter from JavaScript 30 :D