DEV Community

Discussion on: What s wrong with Array.reduce ?

Collapse
 
avalander profile image
Avalander • Edited

The way I see it, it's mostly familiarity bias. reduce will be harder to understand to someone who is not used to it and, well, since anything that can be done with reduce can be done with a for loop, why learn a new construct?

Also, regarding your example, I think a better functional primitive to use here would be partition. Unfortunately, Javascript doesn't have partition out of the box, but it's a function that takes a predicate and a list and returns a list with all the elements for which the predicate evaluates to true and another with all the elements for which the predicate evaluates to false.

The implementation is straightforward with reduce:

const partition = (pred, xs) =>
  xs.reduce(([ t, f ], x) =>
    pred(x)
      ? [ t.concat(x), f ]
      : [ t, f.concat(x) ],
    [[], []]
  )
Enter fullscreen mode Exit fullscreen mode

Or you can take it for instance from ramda.

And then your analyzeResults is just a one liner:

module.exports.analyzeResults = (records = []) =>
  partition(isValid, records)
Enter fullscreen mode Exit fullscreen mode

This is to show that, while reduce is super useful, there are still a lot of functional primitives missing in Javascript, which forces people to use less elegant solutions, and might contribute to the perception of reduce being hard to read.

Collapse
 
dvddpl profile image
Davide de Paolis

very good point. thanx for commenting

Collapse
 
wulymammoth profile image
David

This!! Yes! I actually used reduce in JS and Ruby to partition in the past

Collapse
 
fregante profile image
Fregante • Edited

I created a dev.to account because examples like these are mind boggling. It seems to me that reduce works great for the mathematically-minded and can parse that function very easily, but have to ever stopped and thought about the alternative for-loop? Because to me this looks wildly more readable and it's guaranteed to be more efficient too (no array creation at every loop)

function partition(pred, xs) {
    const partitioned = [[],[]]
    for (const x of xs) {
        partitioned[pred(x) ? 1 : 0].push(x)
    }
    return partitioned
}
Enter fullscreen mode Exit fullscreen mode