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 |
@alFReD-NSH, yeah, good catch!
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:
var b = [[1], 2, [[3], 4], 5, [6, [7, 8]]].reduce(function collect(previous, current) {
return previous +
(Array.isArray(current) ? current.reduce(collect, 0) : current);
}, 0);
@stasm, yep, also a good observation. The initial solution BTW doesn't suffer from this too.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe you can even make it shorter:
Note the second argument of reduce, which will be the previous value for the first iteration, instead of the first element.