You have an array that consists of subarrays that are of varying length. Write a function to find the sum of each element in the array. You may not use any Array methods such as reduce (the only Array method you can use is for checking the type of an element).
The array elements can also contain arrays as their elements (you can have any amount of nesting)
Approach
The initial sum is 0
Check each element in the array
If it is not an array, add it to the sum
If it is an array, add the sum of its elements to current sum
Return the final sum after going through every element in the input array
How do you calculate the sum of the elements in a sub array of sub arrays?
Use the function you are writing!
Possible Solution
function mdArraySum(arr) {
var sum = 0;
for (var i = 0; i < arr.length ; i++) {
if (Array.isArray(arr[i])) {
sum += mdArraySum(arr[i]);
} else {
sum += arr[i];
}
}
return sum;
}