Skip to content

Instantly share code, notes, and snippets.

@christopherhill
Last active December 24, 2015 20:09
Show Gist options
  • Save christopherhill/6855986 to your computer and use it in GitHub Desktop.
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.
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