xamples
epeat
ode
pproach
ptimize
est
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).
mdArraySum([1,2,3,4]); //should return 10
mdArraySum([ [2,4] , [1], [4,2,1] ]); //should return 14
mdArraySum([ 2, [3,4], 5, [-3, [6 , [ 4,5 ] ] ] ]); //should return 26
How do you calculate the sum of the elements in a sub array of sub arrays?
Use the function you are writing!
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;
}
REPL.IT solutions
- Know how recursion/calling a function inside itself works
- Not every problem requires a super long solution (most whiteboarding questions won't)