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.
You're missing two
var
in there. You've implicitly declaredsum
anda
at window scope:The problem with your code is that the
sum
anda
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 wheresum
anda
are declared to make them local to the function:Demo: http://jsbin.com/eGaFOLA/2/edit
Recurse, for example
I didn't optimise this so that it's clear, you may want some more logic before recursion.
The reason yours isn't working is because you need to
var
bothsum
anda
.First of all why you use 'i' as input to function? we using 'i' to denote running index.. Regarding your question,you want 'a' to be local in your loop so instead of "for(a=0;..." instead write "for(var a=0;"
For 2018 this solution is clean and functional:
Documentation for flat and reduce.