Flatten a Nested Array
Why they ask this: Tests recursion and how you handle data of unknown depth, which is common with JSON from APIs.
Problem
Given an array that can contain numbers and other arrays nested to any depth, return a single flat array with all the values in their original order.
Example
Input: [1, [2, [3, [4]], 5], [], 6]
Output: [1, 2, 3, 4, 5, 6]Hints
Approach
Recursive: create an empty result. For each item, if it is an array, flatten it recursively and append its values; otherwise append the item itself.
Iterative alternative: use a stack seeded with the input's items in reverse. Pop an item; if it is an array, push its children in reverse; otherwise append it to the result. This avoids stack overflow for extremely deep nesting.
Built-ins: arr.flat(Infinity) in JavaScript; in PHP, array_walk_recursive can collect the leaf values.
Solution
function flatten(items) {
const result = [];
for (const item of items) {
if (Array.isArray(item)) {
for (const value of flatten(item)) result.push(value);
} else {
result.push(item);
}
}
return result;
}
console.log(flatten([1, [2, [3, [4]], 5], [], 6])); // [1, 2, 3, 4, 5, 6]O(n), n = total number of values and arrays Space O(n + d), d = nesting depthCan you explain this in your own words?