Cross-posted from my website's blog.
Array#reduce, or Array.prototype.reduce (referred to simply as reduce from here on), is my favorite function ...
For further actions, you may consider blocking this person and/or reporting abuse
Great article. It's good to finally see somebody write about reduce in depth.
If you want to see this idea explores further check out
github.com/vanillajs2/absurdum
It's a WIP but it's a lot like lodash except every functional operator is implemented using only reduce.
Thanks!! And thanks for the link. I might update the article to link to this!
Cool. I always appreciate a mention.
You mentioned a bunch of useful operators that aren't in the library. I'll be sure to add those to the roadmap.
Nice summary, thanks for writing it up. "Reduce" is an important concept in many contexts, so if you understand it once, the others will be a lot easier.
I think there's an error in one of the code snippets, where you use this line:
accumulator = reducer(accumulator, this[i], i, array);
I think instead it should be:
accumulator = reducer(accumulator, this[i], i, this);
Because at that point there is no
array
variable.Hi Peter! Thanks for pointing out my mistake! I'll fix it tonight. And yes I agree completely. Reduce is a very important function!
Nice explanation. It is unfortunate that the language must reduce into a new array. D uses the concept called a range, filter and map do not reduce to an array. Instead they are a range the applies on another range. This means map and filter can be applied with (multiple times) and it is still O(n).
Just read about it. Ranges look really useful!
It is funny because Ranges a close to c# LINQ or Java stream. D got to really build its algorithms around it (well technically many types of ranges).
Though coding with lazy evaluation can have its surprises when you're not always aware of the implications.
For example several grouping functions, like chunkBy, require the range to be sorted by the grouping. Sorting is eager, but grouping doesn't need to be. And you can group an unsorted range which could have value... Maybe.
Great post - got a much better understanding of the reduce function now! 👏
I'm so glad the post helped!
Nice post. I also wrote about defining array operations using reduce from a FP perspective: dev.to/homam/reduce-213
Cool, thanks for the link! I'll check it out!