I'm not getting expected results when trying this reduce in JavaScript:
let x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
x.reduce((a,b) => a.length + b.length, []);
Simple, right? Here's what I expect to happen, step-by-step:
----------------------------------------------------------------
| callback | a (accumulator) | b (currentValue) | return value |
----------------------------------------------------------------
| 1st run | 0 | 3 | 3 |
----------------------------------------------------------------
| 2nd run | 3 | 3 | 6 |
----------------------------------------------------------------
| 2nd run | 6 | 3 | 9 |
----------------------------------------------------------------
What do I actually get? NaN. In english, if I understand things correctly, the iterator first looks at the initial value I give it (the empty array as the 2nd argument to reduce) and that is represented by the argument a. My code shows a simple .length on both arguments being added. Where am I going wrong here?
a's first value is[], not0, soa.lengthworks. By returning a number, you're feeding a number into the next iteration, and invoking.lengthon it, which is obviously not your intention.mapandreducevery cleanly:x.map(a => a.length).reduce((a,b) => a + b)