Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created October 7, 2013 01:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 <dmitry.soshnikov@gmail.com>
* 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
Copy link

I believe you can even make it shorter:

[[1], 2, [3, 4], 5, [6, [7, 8]]].reduce(function collect(previous, current) {
  return previous +
    (Array.isArray(current) ? current.reduce(collect) : current);
}, 0); // 36

Note the second argument of reduce, which will be the previous value for the first iteration, instead of the first element.

@DmitrySoshnikov
Copy link
Author

@alFReD-NSH, yeah, good catch!

@stasm
Copy link

stasm commented Oct 7, 2013

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);

@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