Finding the sum of a nested array - Javascript Array Operation

Javascript examples for Array Operation:Array Search

Description

Finding the sum of a nested array

Demo Code

ResultView the demo in separate window

<html>
   <head></head>
   <body> 
      <script>
function arraySum(i) {
    var sum=0;//ww  w  . j a v a 2s  . co  m
    for(var a=0;a<i.length;a++){
        if(typeof i[a]=="number"){
            sum+=i[a];
        }else if(i[a] instanceof Array){
            sum+=arraySum(i[a]);
        }
    }
    return sum;
}
console.log(arraySum([1,2,[3,4],[5]]));

      </script>  
   </body>
</html>

Related Tutorials