Recursion - Sum Nested Array

前端 未结 7 1549
一向
一向 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.

    0 讨论(0)
  • 2021-01-03 13:06
    function arraySum (array) {
      if (array.length > 0) {
        return arraySum(array[0]) + arraySum(array.slice(1));
      }
      if (array.length === 0) {
        return 0;
      } else {
        return array;
      }
    };
    
    0 讨论(0)
  • 2021-01-03 13:11

    Here's a version without using loops:

    function f(arr, i){
      if (i == arr.length)
        return 0;
    	
      if (Array.isArray(arr[i]))
        return f(arr[i], 0) + f(arr, i + 1);
    	  
      return arr[i] + f(arr, i + 1);
    }
    
    console.log(f([1,2,[3,4],[],[5]], 0));

    0 讨论(0)
  • 2021-01-03 13:14

    try with

     function sumItems(array) {
    
      let sum = 0;
      array.forEach((item) => {
        if(Array.isArray(item)) {
         sum += sumItems(item);
        } else {
        sum += item;
        }
      })
      return sum;
    }
    
    0 讨论(0)
  • 2021-01-03 13:15

    This is similar to some of the other solutions but might be easier for some to read:

     function Sum(arr) {
       if (!arr.length) return 0;
       if (Array.isArray(arr[0])) return Sum(arr[0]) + Sum(arr.slice(1));
       return arr[0] + Sum(arr.slice(1));
     }
    
     console.log(Sum([[1],2,[3,[4,[5,[6,[7,[8,9,10],11,[12]]]]]]])) // 78
    
    0 讨论(0)
  • 2021-01-03 13:25

    You could define a callback for using with Array#reduce, which check if an item is an array and uses this function again for that array.

    function add(s, v) {
        return Array.isArray(v)
            ? v.reduce(add, s)
            : s + v;
    }
    
    var array = [1, 2, [3, 4], [], [5]];
    
    console.log(array.reduce(add, 0));

    0 讨论(0)
提交回复
热议问题