Created
October 7, 2013 01:35
-
-
Save DmitrySoshnikov/6861351 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Sum of all elements including nested arrays. | |
* | |
* by Dmitry Soshnikov <[email protected]> | |
* MIT Style License | |
*/ | |
[1, 2, [3, 4], 5, [6, [7, 8]]].reduce(function collect(previous, current) { | |
return ( | |
(Array.isArray(previous) ? previous.reduce(collect) : previous) + | |
(Array.isArray(current) ? current.reduce(collect) : current) | |
); | |
}); // 36 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You might also want to pass a second argument to the inner
reduce
call in order to handle nested arrays whose first element is an array: