DEV Community

Discussion on: You don't need Array.reduce()

Collapse
 
crazy4groovy profile image
crazy4groovy

I think you mean

const add = (a, b) => a + b
const sum = array.reduce(add, 0)

You need a seed value.

Collapse
 
joelnet profile image
JavaScript Joel

Nope. That is exactly what I meant.

The seed is optional. If you don't provide a seed, the first item in the array is given as the accumulator.

Run the code!

const add = (a, b) => a + b

[1, 2, 3].reduce(add) //=> 6
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
fregante profile image
Fregante • Edited

Sum is just about the only case where reduce is useful, but in reality it should never be passed around like that. Why keep an add function around that is only meant to be used together with a reduce? Just wrap it once and never use reduce again:

const sum = (array) => array.reduce((a, b) => a + b);

sum([1, 2, 3]) //=> 6
Enter fullscreen mode Exit fullscreen mode

Don't tell me arr.reduce(add) makes more sense than sum(arr) because it doesn't.

In reality you can write sum event more efficiently with a regular loop and every part of your code benefits.