Created
February 12, 2014 21:05
-
-
Save ryanjadhav/8964492 to your computer and use it in GitHub Desktop.
Sum of Nested number array
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
| var nestedNumbers = [1,2,3,[1,2,3,[12]]]; | |
| var sumOfArray = function(arr, sum) { | |
| for (var i = 0; i < arr.length; i++) { | |
| if (typeof arr[i] === 'object' && arr[i].length) { | |
| sum = sumOfArray(arr[i], sum); | |
| } else { | |
| sum += arr[i]; | |
| } | |
| } | |
| return sum; | |
| }; | |
| console.log(sumOfArray(nestedNumbers, 0)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment