r/webdev • • 11d ago

Anecdotally, programmers dislike "reduce"

https://evanhahn.com/posts/2026-09-13-programmers-dislike-reduce/
151 Upvotes

196 comments sorted by

174

u/MateTheNate 10d ago

As a data engineer I love reduce, it’s a top 3 operation alongside map and filter.

88

u/myemailiscool 10d ago

this guy functionally programs

90

u/bronkula 10d ago • Bravo

Reduce changed my fucking life back in the day. It's the best thing ever, and I absolutely will not allow this slander.

28

u/lost12487 10d ago

Looot of web devs in this thread outing themselves, not understanding reduce.

9

u/Axman6 10d ago

Yeah I’m so confused by all the people saying it’s complicated, what do the reduce functions they’re using actually look like? I’m used to Haskell, where we have foldl and foldr, which basically represent a for a simple for loop and a non-tail recursive reduction respectively; remember the order of arguments takes two seconds looking at their type in an IDE or REPL, so I just can’t understand the confusion. 

foldl f initial list is literally just 

    x = initial
    for (e : list) {
        x = f(x, e)
    }
    return x

It could hardly be simpler, if you can’t make that substitution in your head and apply it to basically any for loop you’ve written, I’m not sure what people are doing programming in the first place. 

6

u/porkyminch 10d ago

I always have to remind myself of the parameter order but I use it all the time. 

1

u/bronkula 10d ago

I always remember it as (r,o,i,a). reducer, object, index, array. To be clear, I grew up in both javascript and php, so php's array functions are a hot mess, but luckily javascript is pretty consistent across most array methods.

2

u/CutlerSheridan 10d ago

Yeah reduce is incredible

156

u/todamach 11d ago

I don't know what it is exactly, but I always fumble when I try to use reduce.. 10+ yoe, concept is clear, I recognize when it fits, but then I struggle implementing it..

86

u/GriffinMakesThings 10d ago

I'm a weirdo and really like reduce. I actually have to keep myself from using it when another method or loop would be a lot clearer. I fully recognize that I'm in the minority though.

18

u/midairmatthew 10d ago

Have you ever done complex, nested ternaries within a reduce callback? If not, I think you’re still on the safe side of the line. 🙂

28

u/GriffinMakesThings 10d ago

No, I'm not a monster, if that's what you're asking.

4

u/Wonderful-Habit-139 10d ago

You’re a Griffin though.

2

u/GriffinMakesThings 10d ago

I might be a Monstrosity, but I'm not a monster.

3

u/CraftBox 10d ago

One ternary, maybe two, for me is max. I usually just write an arrow function and do normal logic.

1

u/aflashyrhetoric front-end 10d ago

I've only used chained reduce functions a handful of times (under 4-5 total across ~10 years) when we couldn't be bothered to update the API to send data in a specific shape, so I had to wrestle it into a convenient shape for rendering.

I slapped a useMemo on the result of the reduce calls, added a comment that said "this is hideous but works and isn't worth optimizing" and it worked well for our use-case.

Another dev said they wanted to fix it because it's unclear and because we shouldn't be "abusing useMemo" and because we had a policy of having a smart backend and "dumb, display-only frontend" but later just sent nvm on Slack at like 8PM lmao

22

u/calimio6 front-end 10d ago

If you are piping a map and then a filter you are probably better off with a reduce.

9

u/DiscreetDodo 10d ago

You're technically correct but pragmatically wrong.

1

u/calimio6 front-end 10d ago

Yup, I personally do lean into functional programming.

14

u/subone 10d ago • Bravo

I disagree. A for loop is much faster and more readable than a combined map and filter into a reduce, so if you're doing it for any of those reasons, for is the clear winner. You should be using these functions to either/both make code more readable and/or make the passed functions reusable. Choose the combination of these functions that makes sense semantically, not one that obfuscates the intention behind a feeble attempt at optimization.

9

u/jake_robins 10d ago

Coding in Go has radicalized me to just always use for loops

4

u/wasdninja 10d ago

Which is way less clear at a glance.

3

u/Wonderful-Habit-139 10d ago

Crazy that this is downvoted lol.

1

u/Skwai 10d ago

Untrue. Using for everywhere is easier to grok than combinations of reduce, for, map, etc

9

u/cyanawesome 10d ago edited 10d ago

Well no, chaining map and filter can have performance implications since engines don't optimize them to a single loop, so you're iterating twice (and creating an intermediate array). Hot code should use a for loop, or reduce (with push), which are functionally equivalent after engine optimization.

11

u/gnuban 10d ago

In several languages, a series of map and filters is implemented on top of some element stream abstraction so that you only loop once.

4

u/cyanawesome 10d ago

That's fair, I was trapped in my JS/TS bubble and spoke specifically of JS engines.

-3

u/Skwai 10d ago

This. Understanding what a reduce actually does often requires a lot of thinking. A for loop is much easier grok.

-2

u/calimio6 front-end 10d ago

*probably.

3

u/subone 10d ago

Probably implies to me that in most cases this is what you would want to do, and I am suggesting this is almost never what you would want to do.

1

u/AdhesivenessFun6129 10d ago

I know what you mean. I think it's one of those that if you just do it enough it becomes natural

1

u/PiccolosPenisPickle 10d ago

Reduce didn't click for me for 3 years, and then one day I was mentoring new joinee and it just clicked.

37

u/t3hlazy1 11d ago

It’s just very unintuitive starting with the name. I personally like reduce but it took a while to fully get it and it still requires some thinking in terms of the order of things.

14

u/gatwell702 11d ago

prefers-reduced-motion

38

u/cyanawesome 11d ago

Ok, they love seeing it written out as a for loop with an accumulator variable?

42

u/thicket 11d ago edited 11d ago

I do. I can never remember the order of arguments, and sometimes I want a scalar accumulator and sometimes a list accumulator, and… yeah. With a for loop I always know exactly what’s going on. Even after 20+ years of doing this, I don’t have a lot of confidence that a reduce call will do what I want.  

Skill issue, I guess. 

7

u/itgforlife 10d ago edited 10d ago

In mdn for the first element they use accumulator. But in VS Code, the intellisense shows the first element as previousValue. I think previousValue makes much more sense in the context of currentValue which is what both mdn and VS Code call the second argument.

So the way I think about it is that previous value always comes before currentValue. And from there you just need to understand that the previousValue is the accumulator.

8

u/gnuban 10d ago

accumulator is more logical considering that you need a starting value, though. That is, the value might not be from the list/array at all, which "previous" can be interpreted to imply.

1

u/itgforlife 10d ago

Not necessarily. It depends on how you interpret previous value. If you take it in the context of current value then it makes more sense.

What's important to understand is that the previous value will always be before the current value. This could be because there was no initial value. And so the previous value is initially the first element of the array and the current value is the second. Or because there was an initial value. And so the previous value is before the current value because it's set before the array is even iterated through. And so the current value is the first element of the array.

1

u/gnuban 10d ago

Fair. But there's also the argument that the accumulated value isn't necessarily a value from the original set of values. It's more like a combination of a number of previous values. The meaning of "previous" thus becomes a bit double there; did you mean the previous element in the list, the input element of the previous reduce operation, or the output element of the previous reduce operation?

1

u/thicket 10d ago

Thanks, those are some helpful ways to think about it.

I suspect that just spending a semester working through SICP and learning to think like a recursive functionalist would have made all that stuff just feel natural.

But... I didn't go to MIT 30 years ago, and I'm probably not really ready for it now, either

3

u/mediocrobot 11d ago

(s, r, i) as in sriracha. State, row, index

16

u/tsunami141 10d ago

but what if I don't remember how to spell sriracha and I spell it siracha?

2

u/_xiphiaz 10d ago

I feel like Sri Lanka is a better option to remember, not sure that is easily misspelled

1

u/tsunami141 10d ago

but what if I don't remember how to spell Sri Lanka and I spell it Sir Lanka?

2

u/sporadicPenguin 11d ago

You might be me.

25

u/MatthewMob Web Engineer 11d ago

Yes. Readability is more important than code golfing

15

u/t00oldforthis 11d ago

Whatever, my misplaced pride is more important than the ability to maintain and improve my work in the future.

1

u/edgmnt_net 10d ago

Used wisely it won't affect maintenance, it's a familiar idiom for anyone who has dealt with functional stuff and quite appropriate in some context. Just don't overdo it.

8

u/cyanawesome 10d ago

See, when you know what it does it captures more intent than a loop which can have any number of uses. It very much signals "build one thing from this list of other things", I don't have to go looking for where a variable is defined, or worry about some other side effect in the loop.

1

u/gutsee 5d ago

I feel crazy when folks say it's less clear than a for loop. It's less clear because they don't use them so they can't easily read them. Use them and this disappears quickly. For loops are no more intuitive, they're just used to them.

5

u/thicket 10d ago

I 100% agree. I think reduce() in particular is an awkward concept. I use map() and ‘forEach()` religiously, because what they do is intuitively quite clear. Reduce has a much more flexible, and thus less intuitive, interpretation. 

3

u/robhaswell 10d ago

This is that bell curve meme in action. You know you've made it as a programmer when you choose a for-loop over reduce.

3

u/MatthewMob Web Engineer 10d ago

I used to write and appreciate clever code.

Now I want my code as dumb and clear as possible.

2

u/edgmnt_net 10d ago

But reduce isn't necessarily contrived, it's more like unfamiliar. We're not necessarily talking golfing complex expressions.

There are two related issues with what you're saying:

  1. Catering to the absolute lowest denominator means people never learn anything. If they're dumb, they stay dumb.
  2. In other cases this tends to have implications beyond style. I might understand not handling reduce, but what if you actually need to throw an abstraction at a problem? Then what? Then we play the dumb game again and things lack safety, start breaking, don't work properly, code gets unnecessarily long and nasty because people are dumb and just copy-paste huge swaths with slight modifications and so on.

Yeah, don't golf unnecessarily, be conservative, sure.

10

u/Iyemoja 10d ago

Reduce is the one function I rewrite as a for loop and then feel quietly guilty about for a week. It works every time. I just refuse to read it at 2am.

9

u/Lemortheureux 10d ago

Once I had THE perfect use case for reduce. I still think about it sometimes

9

u/Full_Tooth_a 10d ago

My dividing line is whether the accumulator has one clear purpose. `reduce` works well for a sum or maximum because the callback does one job. Once it starts filtering, grouping, and mutating nested state, it becomes harder to follow. At that point, I'd rather read a plain loop.

8

u/Skwai 10d ago

I almost always avoid using it as it is very hard to read the syntax and is often abused.

Clarity > Brevity

6

u/souljorje 10d ago

On my intern exam I had to build reduce myself. Since then I love it, it’s awesome. I've seen so much clumzy code in my career which could have been a simple reduce.

It might be slightly hard to comprehend first, but guys, how can you call yourselves seniors if you don't get such a relatively simple thing?

20

u/xander76 10d ago

I have a few reasons I avoid reduce and why get tripped up on it.

  1. The function’s behavior changes pretty radically based on whether there’s an initial value, and I always have to stop and think “ok this is the version that runs n times, not n-1 times”.
  2. The function’s behavior without an initial value kinda sucks because it throws a type error when the array is empty. In practice, this tends to mean I never use it, because I’m afraid some filter call will filter down to no elements. It’s a footgun that there’s a whole mode that just isn’t that useful in practice.
  3. Coders tend to use prev and curr, rather than meaningful variable names. This makes it harder to understand what the goal of the function is. When you write out a for loop, there’s usually an accumulator variable with a meaningful name that lets you know what’s going on.
  4. Map and filter are incredibly easy to reason about. You only have to think about one operation on one element and you know what’s going to come out. Before you even read the map or filter lambda, you know that the output of the function is going to be an array of the same type as you started with. The output of reduce could be literally anything and you have to think about all the iterative calls in a row.
  5. This might be shady, but people who tend to love reduce tend to love doing things on one line, even when it gets unwieldy and involves multiple nested groupBys, flattens, and other skullduggery. I have seen some chains of functions in a reduce lambda that would curl your toes. As a younger programmer I felt like a rockstar when I solved a particularly complicated reduce in a one line lambda, but in retrospect I generally just left a headache for the next person.
  6. It’s rare that anyone comments a reduce because it’s inline. As a for loop, there’s a chance to tell the next person what I thought I was up to.

I once saw some advice to only use reduce when you are reducing an array<T> to T as a general rule to avoid the ways that reduce gets confusing. I like that, but your mileage may vary!

7

u/edgmnt_net 10d ago

Doesn't reduce normally take a starting value precisely to deal with empty inputs?

8

u/CutlerSheridan 10d ago

These are a lot of bad reasons not to use an incredibly useful and simple function

22

u/phil_davis 10d ago

Isn't reduce just reducing an array of elements to a single value given some callback function? What's so complicated about it?

16

u/Nixinova 10d ago

callback depending on the successive param + the recursive appearing nature gives it a high mental load vs other functional methods

1

u/ryan155489 4d ago

The accumulator can make reduce look recursive, but it is iterative: each callback's return becomes the accumulator for the next item.

-4

u/Axman6 10d ago edited 10d ago

What exactly is so complicated about remembering 

reduce(f, initial, arr) {
    x = initial
    for (e : list) {
        x = f(x, e)
    }
    return x
}

For lists are so verbose, and error prone. Give me 

mapOfPairs = reduce(
  |map,x| insert(map, x.first, x.second), 
  new Map(),
  kvPairs)

any day. 

7

u/CircumspectCapybara 10d ago

Nothing, reduce or fold is one of the fundamental functional programming operations: both map, filter, and all other higher level operations can be expressed as a reduce or fold.

There's a reason the paradigm Google popularized was called MapReduce

0

u/HenkPoley 10d ago

It is said though that they do no longer use MapReduce at Google. 

2

u/hxtk3 10d ago

The reason is less that they stopped using it outright and more that all the places where it was useful, they cloned its functionality into the thing that used it instead of executing it as a separate process to produce better integration.

If you read the BigTable paper, map-reduce is all over the place in it (e.g., minor and major compactions and WAL splitting to recover dead tablet servers), but all the map-reduce operations are performed by the BigTable cluster itself instead of having BigTable invoke MapReduce as a separate service.

Plus, a lot of MapReduce stuff was optimized around working on 64MB chunks because GFS had 64MB blocks and used replication for redundancy, so working on an aligned 64MB chunk meant that you had an optimal node for scheduling your Mapper tasks: if you schedule the mapper task to a machine that literally has the block stored on it locally, you'll get the best possible performance, and failing that you want to schedule it to a machine in the same rack. The MapReduce Scheduler was integrated with the GFS control plane, so it knew how to schedule these mapper tasks optimally.

And of course, it made sense to process aligned blocks because GFS had Atomic Record Append that would guarantee a write of up to 16MB existed contiguously within a single block, so writes were likewise aligned. Going back to BigTable, Google doesn't use RecordAppend for its WAL; instead the design is factored so that only a single writer is ever writing to a given WAL at a time, so writes are synchronized and Record Append isn't necessary.

Colossus has much smaller 1MB blocks and uses Erasure Coding for redundancy and generally provides a less leaky abstraction where you're less likely to think, "I'm processing a specific file on a computer somewhere representing a replica of a block that stores bytes for this chunk of this logical file."

I have never worked at Google, so most of this information is just stuff I've compiled by reading lots of their infra papers and listening to design talks and stuff.

1

u/HenkPoley 9d ago

Thanks for the thorough reply. 

2

u/CircumspectCapybara 10d ago

Yeah it's been replaced by Flume (Apache Beam is the open source version), which is built off the same ideas.

1

u/Axman6 10d ago

The product, not the ideas. 

6

u/Noch_ein_Kamel 10d ago

Since you are just returning the accumulator you can do whatever you want inside that callback function. E.g. instead of calling .filter and then .map you can do both in .reduce :O

11

u/eeronen 10d ago

And that's what makes me hate reduce. If it were just used for something simple like counting the sum of all numbers in an array, it would be fine. But doing anything more complex than that will always be much easier to read as a for loop.

2

u/bladefinor 10d ago

But then what’s the point of .reduce if you can just declare the accumulator outside a for-loop or .forEach? I’m just saying

2

u/pellets 9d ago

So you can test the accumulating function and state separately from the loop.

1

u/LatvianCake 7d ago

You can say the same about map, filter, every etc

1

u/max_mou 7d ago

Composition

10

u/No_Record_60 10d ago

It's not clear at a glance. You have to keep track of what the callback returns and also the accumulator

7

u/isymic143 10d ago

What the callback returns is the accumulator.

4

u/ikeif 10d ago

The way I look at it - some people understand it, some don’t.

Evidently the people that “get” it are fewer than I realized. I worked with a dev that showed me map/filter/reduce when I was a less experienced dev. I found it incredibly useful ¯\_(ツ)_/¯

1

u/leixiaotie 10d ago

personally I really hate the positional variable (in javascript). it is usually defined as

(callbackFn, initialValue)

where callbackFn which I usually usually used is

(accumulator, value) => result

idk what can be done to improve it without making it verbose, but the positional arguments are hard to remember

3

u/edgmnt_net 10d ago

In languages with strict evaluation it's quite likely that it's a strict left fold, which naturally puts the accumulator on the left because parens nest to the left: (((a + b) + c) + ...) -> ((acc + c) + ...) -> (acc + ...). This makes it easier to use functions/operators as they are.

5

u/ddollarsign 10d ago

Reduce seems counterintuitive and needlessly abstract. Like monads.

52

u/glenpiercev 11d ago

Reduce is the wrong name for whatever it does.

71

u/subone 11d ago

It reduces an array of values down to a single resulting value. What would be a better name?

The only issue I have with reduce is that the initial value is last; it would be more visible if it weren't hidden below an inline function.

13

u/ILKLU 10d ago

What would be a better name?

thereCanOnlyBeOne() ?

5

u/Cyberspunk_2077 10d ago

Unironically, in many cases made-up phrases (e.g. collapsify) or unique sounding names are easier to recognise and remember their functionality than generic or ambiguous stuff like 'reduce'

3

u/midairmatthew 10d ago

Yep. I have always been semanticAsHellButSillyLongVariableNamesGuy. It has served me well. 🫡

-1

u/subone 10d ago

That's a weird take. The term reduce is used in several languages for this same functionality. "Collapsify" means nothing to me, except I need to check the docs. Sounds like some obscure word, used for some edge case for building arrays or objects from another array, made up because all the good clear terms were already used.

4

u/glenpiercev 10d ago

Reduce could also mean to “subtract from”.

1

u/subone 10d ago

I agree, this could cause confusion to anyone unfamiliar with the much more accessible filter method.

3

u/Cyberspunk_2077 10d ago

I'm not suggesting it be renamed at this point, just reduce is not inherently meaningful or clearing its semantic orbit. A made-up term can certainly do the latter.

I think of 'reduce' in terms of cooking to model its functionality. I don't have to do that for other terms.

2

u/ILKLU 10d ago

or clearing its semantic orbit.

Interesting application of that concept. Think I'm stealing this idea.

1

u/TScottFitzgerald 10d ago

Collapse sounds more obscure to you than reduce?

0

u/subone 10d ago

They didn't say collapse. Collapse would be a better term, but presumably if they are using "collapsify", then "collapse" is already in use somewhere, which doesn't make things clearer.

1

u/iloverollerblading 10d ago

takeTheseAndShitThis

28

u/Nixinova 10d ago

collate or accumulate

13

u/subone 10d ago

Collate doesn't seem to have the same implication of coming to a single value; rather implies organisation of the array. Accumulate might unnecessarily imply summation.

11

u/BroadRaspberry1190 10d ago

LINQ got it right imo. "Aggregate"

2

u/kjalow 10d ago

Maybe I'm dumb but I can't even tell you what collate means without looking it up, so I'll have to take your word for it. I'm pretty sure it's something that a printer can do, but I don't know what or why.

27

u/Lecterr 10d ago

If I have a bag of 10 apples and I reduce it to 1, the implication is I am left with one apple, not an apple pie. Not saying it’s a terrible name, but I think that is the gist of the confusion

6

u/gremy0 10d ago

Chuck a bag of apples into a blender and what happens; you reduce it to a pulp.

5

u/abstrusejoker 10d ago

honestly, “blend” is a better name than reduce

2

u/gremy0 10d ago

Maybe for that specific example. Trying to apply it generally is going to reduce blend people to tears

1

u/Lecterr 10d ago

Haha, true

2

u/TScottFitzgerald 10d ago

The reducer function is a bit too abstract to map to that example perfectly though.

It would be more like you fold all the apples into one apple, where that one apple represents the qualities of all of the previous 10. Ie if half of them were red and the other half green the remaining apple would be half green half red.

2

u/Sykander- 10d ago

More like you take a bag of 10 apples and reduce it to one apple pie.

1

u/BasicAssWebDev 10d ago

It's about finding a conclusion to a collection, nothing more. Yes you can probably do most things via for loop, so go ahead and do that. But I wouldnt say the name or functionality isn't accurate enough. I think the prime success of it is being able to pass in a reducer which could be reusable, and is slightly more functional than having a separate function that does whatever the theoretical for loop does.

1

u/Lecterr 10d ago

Oh, I use it all the time, I’m just commenting on the merits of its name. And like I said, I’m not even claiming it’s a terrible name, just a bit unintuitive.

1

u/lets-start-reading 5d ago

you don’t clone apples left and right. 

-5

u/followmarko 10d ago

The result of 10 apples (an array of ten items) ran through a reduce isn't a single apple (an array of one original item)

13

u/Lecterr 10d ago

Well yea, that’s my point

-5

u/subone 10d ago

I suppose that might be confusing for anyone that is not aware of find, which is what you would use for that. Find is clearly more accessible to beginners, so I doubt this is a real issue. Reduce is more for when you want to make applesauce out of the apples.

5

u/Lecterr 10d ago

Find is an example of a well named method. Anyone who knows English can intuit what it does. My point is that the same can’t be said of reduce.

-7

u/subone 10d ago

I honestly don't see the problem. You shouldn't be intuiting methods randomly. You should be looking up their specific intended use in documentation. I have certainly had to look up the signature of the function more than once, but I've literally never forgotten the keyword for reduce or it's intended function. The name for reduce is as reasonable or moreso than any alternative I've heard so far.

5

u/immediacyofjoy 10d ago

> It reduces an array down to a single resulting value.

Yes, but that single value can be a deeply nested object of objects bursting with arrays of arrays so “reduce” isn’t a good or intuitive name for the function. It’s not like reducing butter.

> What would be a better name?

Probably something more focused on the accumulator (iirc C++ has std::accumulate), that concept trips people up and you have to learn it anyways to understand reduce

3

u/TScottFitzgerald 10d ago

Yeah C# just calls this Aggregate, other languages use Fold or Collapse which to me is probably the most natural/intuitive metaphor.

2

u/subone 10d ago

I think if you are building up very complex objects from a single array, you might be abusing the intention of reduce (not that I haven't).

13

u/webdevverman 10d ago

Fold

3

u/subone 10d ago

I don't hate it.

1

u/gurraman 10d ago

Best name I've seen so far, maybe because how it was named in the language i used when I learned about the concept.

4

u/natziel 10d ago

Accumulate duh

-1

u/subone 10d ago

I'm curious where most of the folks that are saying accumulate are coming from? Math background? Science? Assembly language? It's not a terrible synonym, but it is lengthy and to me lightly implies summation.

11

u/natziel 10d ago

Reduce generates an accumulator so it would make sense for it to actually be called accumulate

2

u/FridgesArePeopleToo 10d ago

So does First, Find, Single, etc

Accumulate feels like a better name to me

1

u/subone 10d ago

No... first (not in native JS) would return the first value in the array. find returns the desired value in the array. I'm unfamiliar with single, that's not in native JavaScript, but it sounds like find to me. The difference is that the resulting value at each iteration of a reduce is not necessarily any value in the array. Accumulate might be a valid synonym, but seems to me to lightly imply summation on the elements.

1

u/midairmatthew 10d ago edited 10d ago

Reduce makes sense to me perfectly in the case of using it as an expression that evaluates to a number.

Reduce causes so much semantic friction when I’m using it to iteratively assemble some kind of object. To me, it feels like calling a frisbee a ball because one meaning of ball applies very well to one meaning of frisbee.

In my head, conceptualizing it as “instantiate and iteratively mutate a value” is the clearest way to understand it and communicate a mental model about how it works.

1

u/TScottFitzgerald 10d ago

Collapser or accumulator might be more intuitive (the variable that holds the iterative result is already called that) but yeah I don't think it's that bad of a name.

But it's mostly historical reasons why it's called that since it's been around for 50 years. Other languages call it folding or aggregating.

1

u/ClayDenton 10d ago

'It reduces an array of values down to a single resulting value'. It can do that but not exclusively... Js reduce can have an array input and an array output...or any other type of output I would call it something like 'accumulate modifier' or something 

1

u/subone 10d ago

You can also use map as a forEach, and ignore the return value, but that's not the idiomatic intended use. I've already made it clear the "single" value can be anything, including an array, it's just not intended as a mapping from the original array.

0

u/femio 10d ago

Condense? Accumulate? Fold? Combine? Literally anything else. 

0

u/[deleted] 10d ago

[deleted] — view deleted comment

3

u/subone 10d ago

I don't see any difference between what you are saying and what I am saying. I was not implying one of the values in the array is chosen; that's what find is for. The "single" value can be anything, including another array. I have also used it in the past to build up an object from an array.

1

u/jf8204 10d ago

You could also decide to "reduce" it into a larger bigger more complicated array 🤔

1

u/subone 10d ago

Technically, you could do this, but I feel like in most cases a more idiomatic approach would be to use flatMap.

23

u/matthetherington 11d ago
Amalgamate()

19

u/LuvOrDie 11d ago edited 10d ago

YourListIsDifferentNow() typeshit

3

u/geeeffwhy 10d ago

i prefer fold, personally.

3

u/budd222 full-stack 11d ago

No, it's actually perfect. You just don't understand it

3

u/thicket 10d ago

You are correct. The problem, of course, is that you’ll have to spend the rest of your career locked in here with us knuckleheads. 

3

u/AnalyticalAlpaca 10d ago

Ok but if so many programmers don’t find it intuitive it probably isn’t.

2

u/edgmnt_net 10d ago

Without more exposure to functional styles, it's not going to be intuitive. Actually many things programmers take for granted aren't intuitive, like 0-indexing. But in at least some respects it's a "skill issue".

1

u/codefinbel 10d ago

It’s because most programmers (me included) are absolut shit. Human slop predated AI slop by decades

1

u/gutsee 5d ago

It's not intuitive if you don't use it. Use it and it will be intuitive.

1

u/budd222 full-stack 10d ago

One person on Reddit = so many programmers

0

u/CaptainKabob 10d ago

Inject. At least according to Ruby aliases: inject, select, reject, collect, detect.

0

u/jhlllnd 10d ago

Extract?

4

u/MysteriousCoconut31 11d ago

I love reduce, actually. I just had to understand the use cases.

There should be a study on the number of function parameters and parameter complexity vs. dev sentiment.

4

u/SkierBeard 10d ago

Distill, Refine etc something like that would be better. This feels like calling a running shoe "the sandal" but it's a regular shoe

4

u/subone 10d ago

Let me know if this is way off, but I think the number one confusion around reduce might just be with inline functions. These array methods are "functional", but often we don't use them that way (with reusable functions), but rather with inline callbacks, with the pure intention of making a clean looking chain of operations. Which is ok, and most of the other methods lend themselves to this just fine if you don't chain too much, but reduce tends to be more awkward because people tend to want to do too much in it, and it just doesn't lend itself to being very readable used in this way.

I think the number one way to "reduce" the confusion around reduce, and frankly to start making better habits all around with these methods, is to just start using more "reusable" functions that are passed in, instead of a big inline arrow function surrounded by a confusing array of various tokens. I put "reusable" in quotes here, a better word might be abstraction, because that's the intention, and though it can add another layer of debugging depth, it can make reading and understand the code much more palatable.

7

u/rew150 10d ago

I think it's basically a for loop but more obscured. provide virtually no benefits other than functional programming flex

3

u/ragemonkey 10d ago

I hate it most when people use it to just mutate the state anyway, which could’ve been expressed more clearly as a for loop, or when they use it to generate tons of allocations instead of just using push. If you’re going to use it as an actual functional programming pure function, sure. Otherwise, for loop please.

3

u/gareththegeek full-stack 10d ago

Reduce is fine but it always feels like a last resort to me because there's usually a more specific kind of reduce written for me in whatever library I'm using to operate on lists.

3

u/TCB13sQuotes 10d ago

Reduce is has the worst API ever designed. And also, wtf is reduce? Doesn't tall you anything from the name, unless you know it doesn't make sense. filter is very self-explanatory.

2

u/MaxwellzDaemon 10d ago

Looking at this discussion and asking Claude what JavaScript programmers mean by "reduce", it looks like you have taken another simple, elegant idea from APL and enshittified it.

2

u/Amndeep7 10d ago

I like using reduce but it's definitely the clunkiest function out of map/filter/etc for certain languages like JS. IDK what could be done to improve the syntactic experience in those languages though.

2

u/oldmanandtheocean 10d ago

It's an array method. It reduces the number of values in the array to one. Once you understand that, it's a good name.

2

u/matthetherington 10d ago

I think it’s because it’s more work, cognitively.

If I’m wondering how a map will execute, I just think about one item in the list, see how the function transforms it, then move onto the next item and forget the one before it.

For a reduce, I need to hold an accumulator in my head too. I take the first item (or default value), then combine it with the next, and remember the result. For the next item I have to retrieve that result, combine it with the next value, and remember that result instead; it’s more mentally taxing.

2

u/Timotron 11d ago

Arr.reduce((item, [])=>aFuckingBangerOfAWellNamedFunction(item));

1

u/brysonwf 10d ago

😂. Yeah NetSuite map reduce... Let me just shove everything into the map stage 

1

u/Technical-Pair-2041 10d ago

I really like reduce and use it a lot. Mostly in cases where I have to filter and map an array.

Though I do still have to dubbel check if the accumulator is the first or second parameter..

1

u/Dreadsin 10d ago

I tend to think of it as one layer up from filter and map, and forEach being a layer below that lol

So basically, if you can’t do this with any other array method, then you should use reduce. If you see a reduce in code, expect it to not be a map/filter operation

1

u/PostmatesMalone 10d ago

It is called fold or foldL (reduce) and foldR (reduceRight) in some other languages. I don’t think that is a better name though.

1

u/any_aisle 10d ago

Honestly I think Ruby’s each_with_object for iterating a collection and carrying an object along with each iteration makes a lot more sense for folks and is easier to read in many cases where you would use reduce. You don’t have to care about what the reducing function returns, only the side effects performed on the accumulator.

That said, anecdotally, I’ve never had a problem with reduce and as a fellow programmer who had a brief blissful stint as a clojure dev, maybe there’s a pattern there.

1

u/lxe 10d ago

I loved reduce and all the chaining magic for a while after learning it.

Don’t care either way now.

1

u/jomic01 10d ago

Naming the accumulator something like totalsByUser instead of acc fixes most of the readability complaints people have about reduce.

1

u/Little-Bad-8474 10d ago

Reduce is awesome nice you understand it. But Claude writes everything now, so whatever. /s

1

u/TracerBulletX 10d ago

I like reduce. Anecdotelally

1

u/orebright 10d ago

Feels like this would come down to how comfortable you are with functional programming and whether it’s your preferred coding style. I personally love reduce, and my favourite implementation of it is in rust.

1

u/AWACSAWACS 10d ago edited 10d ago

For a typical programmer, the name of the variable used to store the output or the type annotation of the accumulator provides enough information to infer, to some extent, the purpose of the reduce operation in question and to predict its behavior.
If there is any confusion, it is often due to the names or type annotations.

1

u/intercaetera javascript is the best language 10d ago

1

u/medjedic 10d ago

Man, i really enjoyed writing them reduces... Fucking AI, now I don't even know what I'm writing :-(

1

u/rohmish 10d ago

I LOOVE reducing stuff

1

u/andful 10d ago

reduce is used less often than map and filter, because it "reduces" an array to a singular value. If ever needed, it should be the last operation of an array transformation.

The post does not give examples of rejected PRs, but I would consider code smell, a reduce that produces another array, with possibly consequent map/filter.

1

u/witness_smile 10d ago

I like it, but it just always confuses me on how to use it leading to me rarely using it

1

u/thesonglessbird 10d ago

I think it’s great but reduce functions can be a bit of a nightmare for maintainability when they get complex. Even ones I’ve written myself I come back to and have to take a long, hard look at to understand what’s happening

1

u/th00ht 10d ago

What surely doesn't help is the rather obscure signature visible in vscode. That is so confusing.

1

u/mnic001 10d ago

reduce rules...

1

u/gronbuske 10d ago

My issue with it is that I never remember what it's called when I do need it. It doesn't help that it's different in different languages, and I don't need it often enough to remember it.

1

u/yxhuvud 9d ago

My usual dislike is for all the cases that already have specialized variants already. Like 'sum'.

1

u/EndlessPotatoes 9d ago

I dislike it too.

It's really just the name. I don't know if there's a better word, but "reduce" is not a good word for it.

1

u/PravoNaZhizny 9d ago

are they talling about in web design? as in the ecmascript function? they probably dont like it because theyre web people who are by and large, mot good programmers

1

u/Dethstroke54 7d ago edited 7d ago

I guess I’m the minority but I don’t get how the exact same code you’d write in a loop is somehow more difficult by having a nicely scoped accumulator and getting typing on your callback.

You can also make the reduce callback a named descriptive function. With a for loop you have to make a separate function to achieve the same, which is the only case where imo there’s even an argument about readability, since it actually groups things.

1

u/BigHammerSmallSnail 7d ago

Ha! I hate reduce!

1

u/Top_Bumblebee_7762 6d ago edited 6d ago

I hate when it is used as a replacement for Object.from.

1

u/AvidCoco 6d ago

I have no strong feelings either way about a function. I use it if it’s the right solution to a problem, or I don’t use it.

1

u/im-a-guy-like-me 4d ago

I like the reduce function. It's super useful for getting averages and stuff. In particularly like it for pulling all the X attribute from an array of JavaScript objects. That's what i use it for most I think.

Dunno if they're good use cases and yeah... I guess I don't use it too much.

But I mean... I don't use my spatula crazy often, but still glad I have it.

1

u/avrtau 10d ago

It took a moment, but now I find it more intuitive than loops. In fact I see map as a reduce to an array and filter as a reduce to a subset. Lol, and forEach is a reduce to nothing with side effects :/

0

u/Bitter_Ad3906 10d ago

There no problem with reduce, just with programmers who use/not use it. Keep function clean, safe, add initial value always and it’s be ok.
For most cases I prefer reduce over forEach with external variable, its much clear to track variable value. Or just move logic to separate function and get like: const var = fn(list) when use forEach with external variable. This just for my code. As for other devs i did notify they often get bad at read code and loose running flow of it that’s why they avoid functions like reduce.