简体   繁体   中英

Reducing an Array of Objects when there is only one Element in the Array

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 (ie "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.

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 ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM