Skip to content

Instantly share code, notes, and snippets.

@crongro
Created December 26, 2014 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crongro/6030c194c62f9909e521 to your computer and use it in GitHub Desktop.
Save crongro/6030c194c62f9909e521 to your computer and use it in GitHub Desktop.
recursive sum using Array reduce
var arr = [1,2,3,[4,5,[4,6,[4,5,[5,[5,[6,100,[21]]]]]]]];
var result = (function getSum(arr) {
var sum = arr.reduce(function(pre,cur,i,o){
if(typeof cur !== "number") {
return pre + getSum(cur);
}
return pre+cur;
});
return sum;
})(arr);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment