Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created October 7, 2013 01:35
Show Gist options
  • Save DmitrySoshnikov/6861351 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/6861351 to your computer and use it in GitHub Desktop.
/**
* 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
@DmitrySoshnikov
Copy link
Author

@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