Skip to content

Instantly share code, notes, and snippets.

@mmloveaa
Created April 1, 2016 17:26
Show Gist options
  • Select an option

  • Save mmloveaa/767b677c40216023cd1c88d5318a3d78 to your computer and use it in GitHub Desktop.

Select an option

Save mmloveaa/767b677c40216023cd1c88d5318a3d78 to your computer and use it in GitHub Desktop.
3 different solutions
// function deepArraySum(array) {
// return array.reduce(function(sum, item) {
// if(typeof item === 'number') {
// return sum + item;
// } else {
// return sum + deepArraySum(item);
// }
// },0);
// }
function deepArraySum(array) {
return array.toString().split(',').reduce(function(sum, str){
var value = parseInt (str) || 0;
return sum + value;
},0);
// if questions didnt state what kind of the item it is, then we need the following solution
// return array.reduce(function(sum, item) {
// if(typeof item === 'number') {
// return sum + item;
// } else if (Array.isArray(item)){
// return sum + deepArraySum(item);
// } else {
// return sum;
// }
// },0);
}
deepArraySum([1,2,3,[4,[5]]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment