Q11: How would you flatten an array completely using a polyfill?
Answer
To flatten an array to any nesting depth, recursively traverse nested arrays until no nested arrays remain.
function flattenDeep(array) {
const result = [];
for (let i = 0; i < array.length; i++) {
if (!(i in array)) {
continue;
}
const value = array[i];
if (Array.isArray(value)) {
result.push(...flattenDeep(value));
} else {
result.push(value);
}
}
return result;
}
console.log(flattenDeep([1, [2, [3, [4, 5]]]]));
// [1, 2, 3, 4, 5]
Explanation
This solution uses recursion and the Array.isArray() check. Each nested array is flattened independently, and its result is appended to the parent result.
The spread operator can hit argument-count limits for extremely large arrays. For production code handling large inputs, append elements iteratively instead.
Key Takeaways
- Deep flattening requires processing nested arrays at every level.
- Recursion is easy to understand, but iterative implementations can avoid call-stack limits.