0

I found this code on http://games.usvsth3m.com/javascript-under-pressure/ and I reach the 5th problem which requires to estimate the sum of all the integer in the list. The list may contains nested lists. So for a list [1,2,3,4,5] or [[1,2,3],4,5] the code below works but for a list [[[[[1]]]],2,3,4] does not. I try a lot of hours and I do not know to solve it. I need a hit plz.

function arraySum(i) {

var sum =0;    
for (var id =0; id<i.length;id++){

    if(typeof i[id]==='object'){

        var ar = i[id];
        for (var dd =0; dd<ar.length;dd++ ){
            if(typeof ar[dd]==='number'){
                sum+=parseInt(ar[dd]);
            }        
        }
    }
    else
        if(typeof i[id]==='number'){
            sum+=parseInt(i[id]);
        }
    }
return sum;
}
b10n1k
  • 567
  • 5
  • 21
  • Wow, I didn't think this was an exact duplicate but I found one. See also [Finding the sum of a nested array](http://stackoverflow.com/q/19181515/1048572) – Bergi Feb 23 '15 at 22:49
  • Thank you for your respond.Should I delete the question due to duplication? – b10n1k Feb 23 '15 at 23:06
  • No, it's fine. The link will serve as a signpost for others with similar questions who wouldn't have found the original. – Bergi Feb 23 '15 at 23:09

1 Answers1

1

use recursion.

var arr = [1, 2, [3, 4, [[[5]]]]];
num = 0;

function loop (arr) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] instanceof Array) {
            loop(arr[i]);
        } else {
            num += parseInt(arr[i]);
        }
    }
}

loop(arr);

console.log(num);

fiddle - http://jsfiddle.net/9j1hcx4x/

Joe Fitter
  • 1,309
  • 7
  • 11