Flatten a nested array
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Implement flatten(array, depth). It returns a new array with the nested arrays inside array flattened into it, up to depth levels deep. When depth is left out, flatten all the way down.
flatten([1, [2, [3, [4]]]])
// [1, 2, 3, 4]
flatten([1, [2, [3, [4]]]], 1)
// [1, 2, [3, [4]]]
flatten([[], [[]], 5])
// [5]Requirements
- Return a new array. Do not change the input array or the arrays inside it.
depthdefaults toInfinity. Withdepth = 0, return a shallow copy.- Only arrays get flattened. Objects, strings,
nullandundefinedare kept as items. - Keep the original order of the items.
Note
Don't use Array.prototype.flat or flatMap: implementing them is the point of the exercise.
Approach
Walk the array once. For each item:
- If it is an array and there is depth left, flatten it with
depth - 1and push its items. - Otherwise push the item as it is.
Recursion matches the shape of the data: every nested array is a smaller version of the same problem, and depth shrinks by one on the way down until it reaches 0.
Use Array.isArray to detect arrays. typeof returns 'object' for arrays, objects and null alike, so it can't tell them apart.
Iterative version
Deeply nested input can overflow the call stack. A stack of [item, depth] pairs avoids recursion:
function flatten(array, depth = Infinity) {
const result = []
const stack = array.map((item) => [item, depth]).reverse()
while (stack.length > 0) {
const [item, level] = stack.pop()
if (Array.isArray(item) && level > 0) {
for (let i = item.length - 1; i >= 0; i--) stack.push([item[i], level - 1])
} else {
result.push(item)
}
}
return result
}Items are pushed in reverse so they come off the stack in their original order.
Complexity
O(n) time and space, where n is the total number of items at every level that gets flattened.
Follow-ups interviewers ask
- Make it a polyfill: add it as
Array.prototype.myFlat, reading the array fromthis. - Sparse arrays:
[1, , 3].flat()skips the hole. Checki in arrayto match that. - Generators: write
function* flattenthat yields items lazily, so very large inputs never build a full result array.
Reference solution
/**
* @param {Array<*>} array
* @param {number} [depth]
* @returns {Array<*>}
*/
export default function flatten(array, depth = Infinity) {
const result = []
for (const item of array) {
if (Array.isArray(item) && depth > 0) {
result.push(...flatten(item, depth - 1))
} else {
result.push(item)
}
}
return result
}type NestedArray<T> = Array<T | NestedArray<T>>
export default function flatten<T>(array: NestedArray<T>, depth = Infinity): unknown[] {
const result: unknown[] = []
for (const item of array) {
if (Array.isArray(item) && depth > 0) {
result.push(...flatten(item, depth - 1))
} else {
result.push(item)
}
}
return result
}