首页 > 解决方案 > How to sum nested arrays in JavaScript

问题描述

I'm trying to create a function that sums the total of all the values in an array, even if those values are nested within nested arrays. Like this: countArray(array); --> 28 (1 + 2 + 3 + 4 + 5 + 6 + 7) I tried this recursive function, but it just concatenates.

var countArray = function(array){
      var sum=0;
      for(let i=0; i<array.length; i++){
              if(array[i].isArray){
               array[i]=countArray(array[i]);
      }
    
          sum+=array[i];
        
        }
      
      return sum;
}

标签: javascriptarraysfunction

解决方案


使用 展平数组Array.flat(),然后使用 求和Array.reduce()

const countArray = array => 
  array.flat(Infinity)
    .reduce((sum, n) => sum + n, 0)

console.log(countArray([1, 2, [3, [4, 5], 6], 7]));


推荐阅读