Tuesday, July 31, 2018

Sum of [1, [2,1], [3,9], 4, 5]



<script>
var arr = [1, [2,1], [3,9], 4, 5];
var  result = arr.reduce(function(sum, current){
if(Array.isArray(current)){
var x = current.reduce(function(xsum, xcurrent){
return xsum + xcurrent;
});
return sum + x;
}
else{
return sum + current
}
});
alert( result ); // 15
</script>

No comments:

Post a Comment

function declaration, expression and call/invoke/execution

  The  function  declaration defines a function with the specified parameters. The  function   keyword can be used to define a function ins...