Recursion - Sum Nested Array

前端 未结 7 1551
一向
一向 2021-01-03 12:24

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         


        
7条回答
  •  迷失自我
    2021-01-03 13:05

    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.

提交回复
热议问题