It seems like an abuse to use .reduce in a way that treats an array or an object (containing two arrays) as "a single output value", especially when the examples in the official docs treats a single output value as either an accumulated sum, or one of the values in the original array.
I find clever tricks almost always more confusing than a more straightforward boring approach (like a for-loop or .forEach). In this case I agree that the filter+map is simplest.
I wouldn't consider the grouping to be a valid use case for ´.reduce´ either. Semantically speaking, it is more a case of filtering an array based on two conditions. Maybe this would be clearer to read:
const isEven = val => val % 2 === 0
const isOdd = val => val % 2 === 1
const ar = [1, 2, 3, 4, 5]
return {
even: ar.filter(isEven),
odd: ar.filter(isOdd),
}
In general, I find it helpful to do one thing twice, than to do two things at once. It also follows the single responsibility principle for functions.
I would perhaps keep the sections in, but before every example just include an Update: Due to insightful comments, I no longer recommend this approach:.
Thanks for your post, and for your thoroughness in following up!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I was thinking about the filter+map example. But the grouping example is also a candidate.
The official docs say:
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
developer.mozilla.org/en-US/docs/W...
It seems like an abuse to use
.reduce
in a way that treats an array or an object (containing two arrays) as "a single output value", especially when the examples in the official docs treats a single output value as either an accumulated sum, or one of the values in the original array.I find clever tricks almost always more confusing than a more straightforward boring approach (like a
for-loop
or.forEach
). In this case I agree that the filter+map is simplest.I wouldn't consider the grouping to be a valid use case for ´.reduce´ either. Semantically speaking, it is more a case of filtering an array based on two conditions. Maybe this would be clearer to read:
In general, I find it helpful to do one thing twice, than to do two things at once. It also follows the single responsibility principle for functions.
I would perhaps keep the sections in, but before every example just include an
Update: Due to insightful comments, I no longer recommend this approach:
.Thanks for your post, and for your thoroughness in following up!