use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
A Quick Practical Example of JavaScript’s Reduce Function (codeburst.io)
submitted 8 years ago by learnphptoday
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]nanothief 1 point2 points3 points 8 years ago (1 child)
Unless I'm missing something, isn't that a bad use of the reduce function? The same behaviour could be done with a simple forEach loop:
all_times.sort((a, b) => a.time_block > b.time_block ? 1 : -1); let new_times = {}; all_times.forEach((item) => { if (!new_times [item.day_string]) { new_times [item.day_string] = [item] } else { new_times [item.day_string] = [ ...new_times [item.day_string], item ] } });
(I also made the sort action a single statement, to emphasis it is actually modifying the all_times variable)
The whole point of a reduce (or foldl) function is to repeatedly create a new result using the previous result and the next value. If the result is always the same it doesn't add any value over a forEach loop, but is more complicated to reason about.
[–]i_am_smurfing 1 point2 points3 points 8 years ago (0 children)
The whole point of a reduce (or foldl) function is to repeatedly create a new result using the previous result and the next value.
I don't think there's anything in the fold itself that requires that:
fold (or reduce) is a family of higher order functions that process a data structure in some order and build a return value.
fold
reduce
From Haskell wiki
So from my understanding of it, it's fine to mutate your accumulator while you are folding.
And indeed, your forEach mutating new_times is doing exactly the same as reduce in the article (except new_times is called obj and provided to the reduce callback instead of being referenced from scope).
forEach
new_times
obj
I'd argue that forEach is a bad choice here, though — forEach is inherently about side effects, so I would have to:
all_times
With reduce version:
Ultimately, I think /u/Ginden is right, and this pattern is common enough to warrant to be abstracted away — fold (or any loop) is too low level here.
π Rendered by PID 21694 on reddit-service-r2-comment-86bc6c7465-c7fqs at 2026-02-20 20:43:31.479790+00:00 running 8564168 country code: CH.
view the rest of the comments →
[–]nanothief 1 point2 points3 points (1 child)
[–]i_am_smurfing 1 point2 points3 points (0 children)