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?
Introduction to the JavaScript Array reduce() method The script is simple and straightforward: First, declare an array of three numbers 1, 2 and 3. Second, declare the sum variable and set its value to zero. Third, in the for loop, add up the elements of the numbers array to the sum variable.
const sum = values. reduce((accumulator, currentValue) => { return accumulator + currentValue; } , 0); As you can see, the reduce method executes the call back function multiple times. For each time, it takes the current value of the item in the array and sum with the accumulator.
The reduce() method executes the function for each value of the array (non-empty array) from left to right. The reduce() method has the following syntax: let arr = [];arr. reduce(callback(acc, curVal, index, src), initVal);
JavaScript Array reduce() The reduce() method executes a reducer function for array element. The reduce() method returns a single value: the function's accumulated result. The reduce() method does not execute the function for empty array elements. The reduce() method does not change the original array.
I think this is what you're trying to do (variables renamed for clarity):
let x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
x.reduce((acc,element) => acc + element.length, 0);
This is how it would happen step-by-step:
--------------------------------------------------------------
| callback | acc | element | element.length | return value |
--------------------------------------------------------------
| 1st run | 0 | [1, 2, 3] | 3 | 3 |
--------------------------------------------------------------
| 2nd run | 3 | [4, 5, 6] | 3 | 6 |
--------------------------------------------------------------
| 3rd run | 6 | [7, 8, 9] | 3 | 9 |
--------------------------------------------------------------
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With