1

I have a simple collection:

[{a: 1}, {a: 2}, {a: 3}]

How do I use Lodash's reduce to get the sum of all "a" attributes?

This seems like a trivial / canonical use, but I can't get the syntax right and surprisingly can't find any docs beyond Lodash's example.

Using Lodash's docs example, it should be:

const total = _.reduce([{ a: 1}, {a: 2}, {a: 3}], (sum, elem) => elem.a);

However this returns the value "3" instead of "6'.

Note: I'm specifically asking about the usage of reduce. I'm aware of other methods like the one in this question.

Community
  • 1
  • 1
Don P
  • 60,113
  • 114
  • 300
  • 432

1 Answers1

5

You're forgetting to add sum to elem.a. Also, you need an initial reduction, otherwise, sum will be initialized to { a: 1 }:

_.reduce([{ a: 1}, {a: 2}, {a: 3}], (sum, elem) => sum + elem.a, 0);

You might want to look at sumBy() for this too. It's the same reducer, only more concise:

_.sumBy([{ a: 1}, {a: 2}, {a: 3}], 'a');
Adam Boduch
  • 11,023
  • 3
  • 30
  • 38