christopherhill
10/6/2013 - 4:23 PM

This was derived from a little game on-line; it uses recursion to sum a nested array of dynamic elements.

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;
}