JavaScript array reduce to sum lengths of sub-arrays - why doesn't this work?
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 |--------------------------------------------------------------
The .reduce()
API expects that your callback function will return the accumulator value (in your case, the value that starts off as []
). Your callback just returns a value.
To make your code work, you'd need something like:
x.reduce((a,b) => { a.push(a.length + b.length); return a; }, []);
Now, if what you really want is a sum of the lengths of the arrays, then you don't want to accumulate into an array anyway; you want a simple sum. Instead of having the accumulator be an array then it just needs to be a number:
var sum = x.reduce(((sum, array) => sum + array.length), 0);
Start with zero, and each call to the function adds the array length to the sum.
As an alternative to using reduce
, flatten the array and take the length of the result.
function flatten(a) { return [].concat(...a); }const x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];const length = flatten(x).length;console.log(length);
The implementation of flatten
above is for arrays which have depth of one or two. Extend/replace it as necessary for more deeply nested arrays.