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.
This can be done with lodash
_.flattenDeep
and_.sum
: