I wanted to do a recursive function in order to add an array.
Here's the sample array I'm trying to use:
[[[1, 2, [[3], 4]], 5, []]]
Since I'm learning, I wanted to try it with reduce... And it's working great, sometimes:
const sumItems = function(array) {
return array.reduce(function(acc, x) {
return acc + (Array.isArray(x) ? sumItems(x) : x);
},0);
};
The thing is, I would've loved to be able to shorten it... Something like so:
const sumItems = function(array) {
const reducer = (acc, x) => (acc || 0) + (Array.isArray(x) ? sumItems(x) : x);
return array.reduce(reducer);
};
But that's not working at all... I'm not sure why and although I've been playing around with my code, console logging it etc etc etc, the best I can get is an output like this:
[ [ 1, 2, [ [Array], 4 ] ], 5, [] ]
Which I find really interesting...
Does someone knows how I could resolve this? Am I doing something wrong that I'm not yet aware of, regarding JavaScript?
Thank you for your time