FlattenLoading saved progress…

Flatten

You're given an array that may contain nested arrays, nested any number of levels deep. Implement flatten(arr) so it returns a new array with all nesting removed — every value pulled up to a single, flat level. The native version is Array.prototype.flat(Infinity); your job is to write the recursion yourself.

Signature

// Returns a new array with every nested array fully unwrapped.
// Does NOT mutate the input.
function flatten(arr: any[]): any[];

Examples

flatten([1, 2, 3]);                  // [1, 2, 3]
flatten([1, [2, 3]]);                // [1, 2, 3]
flatten([1, [2, [3, [4]]]]);         // [1, 2, 3, 4]
flatten([[[[[5]]]]]);                // [5]
flatten([]);                         // []
flatten([1, [], [2, [3, []]]]);      // [1, 2, 3]
flatten([1, 'a', [true, [null]]]);   // [1, 'a', true, null]

Notes

  • Depth is unlimited. Match Array.prototype.flat(Infinity) — there is no depth argument here, you go all the way down.
  • Skip holes. Sparse positions ([1, , 3]) are dropped, the same way the native flat drops them. Explicit undefined ([1, undefined, 3]) is kept.
  • Only plain arrays unwrap. Use Array.isArray to decide. Objects, strings, typed arrays, and array-likes ({ 0: 'a', length: 1 }) stay as-is.
  • Do not mutate the input. Return a brand new array. The caller's nested structure must be intact afterwards.
  • Don't reach for arr.flat(). The whole point is to write the recursion. flat, flatMap, and JSON.parse(JSON.stringify(...)) are off-limits.
Loading editor…