Skip to content

Instantly share code, notes, and snippets.

@mmloveaa
Last active April 3, 2016 07:04
Show Gist options
  • Select an option

  • Save mmloveaa/b8aba62fd32902456f751da2848bc92a to your computer and use it in GitHub Desktop.

Select an option

Save mmloveaa/b8aba62fd32902456f751da2848bc92a to your computer and use it in GitHub Desktop.
4-1 DeepArraySum
Complete the given function deepArraySum that will add all of the numbers in a deeply nested array. The array may be nested arbitrarily deep, and may have numbers at any depth. The function should return the sum of all numbers found at any depth.
All arrays will contain either integer numbers, arrays, or nothing.
If an array is empty or it doesn't contain any numbers, it should have a sum of zero.
Input Format:
The function will have one function
array - an arbitrarily nested array.
Output Format:
The function will return a number representing the sum of all numbers found in the array, at any depth.
Sample Input 1:
[1,2,3,[4,[5]]]
Sample Output 1:
15
Sample Input 2:
[2,[[2,[[2,[[2],2]],2]],2]]
Sample Output 2:
14
Sample Input 3:
[[],[[]],[[[]]]]
Sample Output 2:
0
function deepArraySum(array) {
var total = 0;
for(var i=0; i<array.length; i++){
if(Array.isArray(array[i])){
total+= deepArraySum(array[i])
}
else {
total += array[i]
}
}
return total
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment