Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the sum of a nested array

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;
}

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

like image 906
user2846577 Avatar asked Sep 17 '25 19:09

user2846577


2 Answers

The problem with your code is that the sum and a variables are global, instead of local. Because of this you get an infinite loop (a from the first entry in the function is reset by the second entry, so the same elements are processed again).

Fix it by adding var to where sum and a are declared to make them local to the function:

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

Demo: http://jsbin.com/eGaFOLA/2/edit

like image 105
Tibos Avatar answered Sep 19 '25 09:09

Tibos


I know it's late, but they say "is never late" :)

const sumNestedArray = arr => arr.flat(Infinity).reduce((a,b)=> a+b, 0)

const sumNestedArray = arr => arr.flat(Infinity).reduce((a,b)=> a+b, 0)

console.log(sumNestedArray([1,[2], [2, 3, [4]]]))
sumNestedArray([1,[2], [2, 3, [4]]])
like image 23
Th1 Avatar answered Sep 19 '25 09:09

Th1