Let's say I have this:
function arrSum(){
*code here*
}
How do I write the arrSum function such that it can sum all the integers within a multidimensional array (of variable depth).
I.e.
arrSum([2, 5, [4, 6], 5]) === 22;
I know there must be an answer to this somewhere but I really can't find it. If this is a duplicate please let me know.
Simply you can write a function like this with recursion
function arrSum(arr) {
var sum = 0;
// iterate array using forEach, better to use for loop since it have higher performance
arr.forEach(function(v) {
// checking array element is an array
if (typeof v == 'object')
// if array then getting sum it's element (recursion)
sum += arrSum(v);
else
// else adding the value with sum
sum += v
})
// returning the result
return sum;
}
console.log(arrSum([2, 5, [4, 6], 5]) === 22);
Using for
loop
function arrSum(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] == 'object')
sum += arrSum(arr[i]);
else
sum += arr[i];
}
return sum;
}
console.log(arrSum([2, 5, [4, 6], 5]) === 22);