1

Lets say I have this array [{num:1}, {num:2}, {num:3}]. I can do the following -

[{num:1}, {num:2}, {num:3}].reduce((a, b) => a.num === undefined? a + b.num : a.num + b.num)

I get "6", great! However if my array only has one element (say I'm dynamically filling my array using a loop and need to reduce during each iteration) something like [{num:1}] and do the same -

[{num:1}].reduce((a, b) => a.num === undefined? a + b.num : a.num + b.num)

I get "{num: 1}" which makes sense (if there is only one element return that element).

So is there any way I can use the reduce function and get the "correct" answer (i.e. "1") for the above answer.

I realise I could just create my own function (looping round the array, summing as I go and return the total) but I am interested to see if it is possible to use the reduce function.

2 Answers 2

5

Yes, you can provide an initial value of 0:

array.reduce(
  (a, b) => a + b.num,
  0 // <-- initial value
);

It will work for empty arrays too (returning 0).

Sign up to request clarification or add additional context in comments.

1 Comment

Annoyingly simple, Thanks!
1

Two answers:

1)

[{ num: 6 }].reduce(function (a, b) { return a + b.num; }, 0);
// note the starting-value for A, passed into reduce.

2)

[{ num: 6 }].map(el => el.num).reduce((a, b) => a + b, 0);
// I should still pass the starting-value,
// but here I've mapped all of the elements first,
// into the same type that the reduce is expecting,
// thus simplifying the reduce to be a simple add function

1 Comment

I like the out-of-the-box thinking of the map answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.