Created
April 1, 2016 17:26
-
-
Save mmloveaa/767b677c40216023cd1c88d5318a3d78 to your computer and use it in GitHub Desktop.
3 different solutions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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