DEV Community

Cover image for Master the Javascript Array Reduce Method with 10 Examples

Master the Javascript Array Reduce Method with 10 Examples

Ramiro - Ramgen on September 20, 2021

The Javascript reduce method is a powerful tool that allows developers to iterate over an array and accumulate a single value or object. In this tu...
Collapse
 
ramgendeploy profile image
Ramiro - Ramgen • Edited

Those are awesome suggestions, the post was more to have examples on how to use reduce than the most performant way of doing things ๐Ÿ˜…,
as reduce is widely used on react and it's really useful to know how the vanilla javascript method works,
but yea knowing the best way of doing things is important.
I appreciate the time you have put in the comment, Thanks ๐Ÿ˜„

Collapse
 
fbolaji profile image
Francis.B

I rarely use Reduce in react as there more efficient methods to manipulate data as @lukeshiru mentioned.
I personal use all eas6 methods in React most of the time:
.filter()
.map()
new Set()
.find()
.findIndex()
.includes()
Object.is()
[].entries()
[].keys()
[].values()
.sort()
and untility library such as lodash
then occasionally .reduce() .some()

Thread Thread
 
ramgendeploy profile image
Ramiro - Ramgen

I also rarely use reduce in react, but I was working with the context api the other day and it really was useful to know how the reduce method worked to understand the api (at least the part where there is reduce like syntax), but yea with array manipulation reduce is at the bottom of the list ๐Ÿ˜…

Collapse
 
pengeszikra profile image
Peter Vivo

reducer in React means total different things, than array reduce function ... which is really useful tool as you described. reducer in React means pure function which modify state by action payload.

Thread Thread
 
ramgendeploy profile image
Ramiro - Ramgen

Yes you are correct, they are not the same, Thank for the comment.

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

On your summing example, you're providing the initial value of 0 which isn't necessary - and actually makes it slightly less efficient. If you omit the initial value, the first value of the array will be used instead - reduce will then proceed from the second item in the list

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Omitting the initial value is an antipattern that makes your code much harder to reason about. Let's say you want to concatenate digits into a string (deliberately oversimplified example, you'd just use join for this in real life):

const zeroDigits = []
const oneDigit   = [1]
const twoDigits  = [1, 2]

zeroDigits.reduce((a, c) => String(a) + String(c)) // throws TypeError
oneDigit  .reduce((a, c) => String(a) + String(c)) // number 1
twoDigits .reduce((a, c) => String(a) + String(c)) // string '12'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

Being 'hard to reason about' is purely subjective, and down to the individual. It's a perfectly valid language feature that has a valid use.

Thread Thread
 
lionelrowe profile image
lionel-rowe • Edited

You can't possibly be arguing that saving the 2 or 3 minified bytes from writing ,0 or ,'' or the amount of processing power required to add zero to something is somehow worth the likelihood of your code taking a single input type and outputting two unrelated types or throwing an error?

I notice your reverseStr function from your other comment suffers from this problem โ€” did you realize that when you wrote it?

const reverseStr = str => [...str].reduce((a, v) => v + a)

reverseStr('') // throws TypeError
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

Yes

Collapse
 
ramgendeploy profile image
Ramiro - Ramgen

Right! I forgot to mention that, nice catch ๐Ÿ˜„

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

Might want to re-check the summation and multiplication section - still some issues there

 
ramgendeploy profile image
Ramiro - Ramgen

Yes you are correct, those are not the same, but useReducer, has the same idea behind so it really useful to understand array.prototype.reduce to understand things like useReducer.
Well I guess I need to do more thinking then ๐Ÿ˜…

Thread Thread
 
fbolaji profile image
Francis.B

I understand both of your arguments and illustrate of how .reduce() works.

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

Reverse a string:

const reverseStr = str=>[...str].reduce((a,v)=>v+a)
Enter fullscreen mode Exit fullscreen mode

Convert a binary number in a string to a decimal:

const bin2dec = str=>[...str].reduce((a,v)=>+v+a*2,0)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ramgendeploy profile image
Ramiro - Ramgen

Oh nice adding these examples to the post, Thanks!

 
ramgendeploy profile image
Ramiro - Ramgen

For sure, I'm basicaly refering to the context api, it uses reduce as one of the main methods and it useful to know how .reduce works. Also if I'm not wrong useState uses useReducer at the backend but I can be mistaken, but anyways the useReducer hook can be used instead of useState when you have complex logic.

And you are right, you have to use the right tool for the right problem, I'm not arguing with that ๐Ÿ˜ƒ
Although, I'm not sure if I'm on the same page with "generally there is a better solution than useEffect and useRef", those are really useful hooks that in the most part will do a fine job at any problem.

Collapse
 
suchitra_13 profile image
Suchitra

Nice article!!
Btw I wanna ask you that which markdown format you used for the code color them cuz whenever I used to code it simply displayed in write colored text!
Please specify:)
though it is out of the topic question:P

Collapse
 
ramgendeploy profile image
Ramiro - Ramgen • Edited

Thanks! to have the code with the right color format you do
ยดยดยดjavascript <- language name here
let data=[]
...
ยดยดยด
Here change the commas for the right ones, this is to not have this comment formatted, the right ones are these `

Collapse
 
suchitra_13 profile image
Suchitra

Thanks I will try!

Collapse
 
lionelrowe profile image
lionel-rowe

There's a great HTTP 203 video about that here: Is reduce() bad? - HTTP 203

The title is maybe a little clickbait-ey, but they do make a pretty good reasoned argument for "yes... mostly" and give some great examples for how to rewrite such code in more readable ways.

Collapse
 
shriyastout profile image
ShriyaStout

These are the best and most effective suggestions shared by you here , thanks for your help. dua to make someone talk to you again

Collapse
 
janiceperry profile image
JanicePerry

The reduce() method executes a user-supplied โ€œreducerโ€ callback function on each ... This is shown in the following interactive example. white magic for love

Collapse
 
wegissilveira profile image
wegissilveira

Thank you, man.

Have a better understanding of Reduce has been on my todo list for a while. You really helped me with this article.

Collapse
 
ramgendeploy profile image
Ramiro - Ramgen

Thanks! Glad you like it ๐Ÿ˜

Collapse
 
qq449245884 profile image
qq449245884

Dear Ramiro๏ผŒmay I translate your article into Chinese?I would like to share it with more developers in China. I will give the original author and original source.

Collapse
 
ramgendeploy profile image
Ramiro - Ramgen

Sure, that'll be awesome ๐Ÿ˜