Exploring the idea of a recursive function to sum up an array.
Here's the array structure I'm experimenting with:
[[[1, 2, [[3], 4]], 5, []]]
As I delve into learning, I decided to implement it using reduce... and it's been quite successful, albeit with occasional hiccups:
const sumItems = function(array) {
return array.reduce(function(acc, x) {
return acc + (Array.isArray(x) ? sumItems(x) : x);
}, 0);
};
Looking to streamline it further, I attempted a more concise approach:
const sumItems = function(array) {
const reducer = (acc, x) => (acc || 0) + (Array.isArray(x) ? sumItems(x) : x);
return array.reduce(reducer);
};
However, this approach didn't quite yield the expected results. Despite multiple attempts and console logging, I ended up with output like this:
[ [ 1, 2, [ [Array], 4 ] ], 5, [] ]
An intriguing discovery indeed...
If anyone has insights on how to address this issue, I'd appreciate the guidance. Could I be missing a key concept in JavaScript?
Thanks for your input