Flattening N-level Nested Arrays in JavaScript

At a recent interview I was asked to write a function to flatten a nested array in JavaScript using the reduce method. I am familiar with reduce and how to use it, but was not so sure how to use it for this problem, taking into account the N-level depth part of the question. There is a language agnostic algorithm for recursively walking an array, but the interviewers were looking specifically for a solution that incorporated JavaScript’s reduce method. Anyway, after I got home I played around with the problem on codepen for a while and looked at some solutions provided by others, and came up with my own implementation. Here is a gist with both a classic “array walk” implementation (which can be implemented in pretty much any language), and one using reduce:

Both methods use recursion to handle the N-level depth problem, but for my tastes the classic solution is a lot more readable. It took me a while, even looking at examples to really understand what is happening with the reduce implementation. This could also be because I haven’t really used reduce or some since I read about them in Eloquent JavaScript. Regardless, it was a nice learning opportunity for me to actually play around with some of the modern array methods.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.