Flatten I
Flatten Arrays Recursively and Iteratively (Algorithmic) (Easy, [Google, Amazon, Netflix, Meta+], Video]
Write a function to flatten a multi-dimensional array into a single-level array. Provide both recursive and iterative solutions.
The flattenRecursively()
and flattenIteratively()
functions take an input value and return a flattened array of all its elements.
flattenRecursively()
uses recursion to flatten nested arrays. If the input value is an array, it recursively calls flatten()
on each of its elements and pushes the returned elements into the results
array. If the input value is not an array, it is directly pushed into the results
array.
flattenIteratively()
uses an iterative approach to flatten nested arrays. It creates a stack initialized with the input value and keeps popping elements from the stack until there are no elements left. If the current element is an array, it adds all its elements to the stack. If the current element is not an array, it is added to the front of the results
array using unshift()
. Finally, the results
array is returned.