Finding the sum of a nested array

2019-06-02 09:01发布

I tried finding the sum of all numbers of a nested array, but I don't get it to work correctly. This is what I tried:

function arraySum(i) {
    sum=0;
    for(a=0;a<i.length;a++){
        if(typeof i[a]=="number"){
            sum+=i[a];
        }else if(i[a] instanceof Array){
            sum+=arraySum(i[a]);
        }
    }
    return sum;
}

Does somebody know where there is a mistake in it? When you try it out with the array [[1,2,3],4,5], it gets 6 as answer, instead of 15. I don't know why.

7条回答
Emotional °昔
2楼-- · 2019-06-02 09:39

This can be done with lodash _.flattenDeep and _.sum:

const arr = [[1, 2, 3], 4, 5];
arraySum(arr);

function arraySum(arr) {
  var arrFlattens = _.flattenDeep(arr);
  // => [1, 2, 3, 4, 5]
  console.log(_.sum(arrFlattens));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

查看更多
登录 后发表回答