I\'m trying to sum a nested array [1,2,[3,4],[],[5]]
without using loops but I don\'t see what\'s wrong with what I have so far.
function sumItem
You may do as follows;
var sumNested = ([a,...as]) => (as.length && sumNested(as)) + (Array.isArray(a) ? sumNested(a) : a || 0);
console.log(sumNested([1,2,3,[4,[5,[6]]],7,[]]));
The function argument designation [a,…as]
means that when the function is fed with a nested array like [1,2,3,[4,[5,[6]]],7,[]]
then a
is assigned to the head which is 1
and as
is assigned to the tail of the initial array which is [2,3,[4,[5,[6]]],7,[]]
. The rest should be easy to understand.