Last active
December 24, 2015 20:09
-
-
Save christopherhill/6855986 to your computer and use it in GitHub Desktop.
This was derived from a little game on-line; it uses recursion to sum a nested array of dynamic elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function arraySum(i) { | |
// i will be an array, containing integers, strings and/or arrays like itself. | |
// Sum all the integers you find, anywhere in the nest of arrays. | |
var intTotal = 0; | |
for (var j = 0; j < i.length; j++) | |
{ | |
if (typeof(i[j]) === 'number') { | |
intTotal += i[j]; | |
} else if (typeof(i[j]) === 'object') { | |
if (i[j].constructor.name = 'Array') { | |
results = arraySum(i[j]); | |
intTotal += results; | |
} | |
} | |
} | |
return intTotal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment