Skip to content
Advertisement

Iterative solution for flattening n-th nested arrays in Javascript

Can anyone show me an iterative solution for the following problem? I solved it recursively but struggled with an iterative solution. (Facebook Technical Interview Question)

JavaScript

Solution must work with n-th nested array elements (i.e. it must still work if someone modifies the array values/placement in the example above)

Recursive solution:

JavaScript

Advertisement

Answer

Here is one way:

JavaScript

Explanation: If iterating over a nested structure, you just have to remember where you were before by saving the current array and position before moving into the nested array (this is usually taken care of via the stack for recursive solutions).

Note: If you reuse the arrays placeHolder and lastIndex you won’t need to keep recreating them every time. Perhaps something like this:

JavaScript

This is even faster again (for flat iteration that is), and less garbage collector issues calling it many times. The speed is very close to that of recursive function calling in Chrome, and many times faster than recursion in FireFox and IE.

I recreated Tomalak’s tests here since the old jsPerf is broken for editing: https://jsperf.com/iterative-array-flatten-2

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement