The most common thing I use reduce() for is producing Strings as output, by looping over and processing a list of some kind of data. I might be doing something like:
Array of data into a String of HTML sourceNodeList of elements (like what gets returned from document.querySelectorAll()) in a webpage into a String of CSS sourceCSSStyleSheet into a String of CSS sourceArray of data into other formats (CSV, MD, TXT, JSON, JS, etc) and sometimes also outtputting that as data URIsI think the only time I've used it on numbers has been as a demo summing an Array of numbers to show what it can do, not for anything I've actually needed yet :D
Loved your Topic, even i am interested in .reduce()
The first Example will be hard for the starters to understand, So here's my Version!
var arr = [1,2,3,4,5];
arr.reduce(function(accumulator, nextValue){
return accumulator + nextValue;
});
This will generate the following result
accumulator nextValue returnedValue
1 2 3
3 3 6
6 4 10
10 5 15
And Hence the result will be 15
var arr = [1,2,3,4,5];
arr.reduce(function(accumulator, nextValue){
return accumulator + nextValue;
},10);
It will generate the following. Keep in mind, if the second parameter is passed then this is treated as the first value in the array
accumulator nextValue returnedValue
10 1 11
11 2 13
13 3 16
16 4 20
20 5 25
I hope you find my answer helpful, please do like and comment it gives me the confidence to be more helpful and innovative😇
Joseph S Stevens
10 years of Software Development, Husband, Father and Functional Programming enthusiast.
Good read!