Code Logo

Flatten Nested with Array.flat()

Published at25 Jul 2026
JavaScript Collections Hard 0 views
Like0

Write a JavaScript function that uses Array.flat() to flatten a nested array. The function takes an array and a depth parameter, and returns a new array flattened to that depth using the flat() method. If depth is Infinity, all nesting levels are flattened.

Array.prototype.flat() was introduced in ES2019 and creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. Unlike manually writing recursive flattening loops, flat() provides a declarative way to control flattening depth with a single parameter. Without arguments, flat() defaults to depth 1.

The flat() method is the modern replacement for older flattening patterns like reduce.concat and apply.concat. It handles empty slots correctly (removes them), works with any iterable elements, and is more readable than manual flattening. flatMap() combines map() and flat() in a single efficient operation.

Time complexity is O(n) where n is the total number of elements across all nesting levels. Space complexity is O(n) for the new flattened array. The method does not mutate the original array.

Edge cases include depth 0 (returns a shallow copy), depth Infinity (fully flattens all nesting), empty arrays (returns empty array), and sparse arrays (empty slots are removed by flat).

Example Input & Output

Example 1
Input
[[1],[2],[3]],0
Output
[[1],[2],[3]]
Explanation

Depth 0: no flattening

Example 2
Input
[],2
Output
[]
Explanation

Empty array

Example 3
Input
[[1,2],[3,[4,5]]],1
Output
[1,2,3,[4,5]]
Explanation

Depth 1: only first level flattened

Example 4
Input
[1,[2,[3,[4]]]],Infinity
Output
[1,2,3,4]
Explanation

Infinity depth: all levels

Example 5
Input
[[1,2],[3,[4,5]]],2
Output
[1,2,3,4,5]
Explanation

Depth 2: fully flattened

Algorithm Flow

Recommendation Algorithm Flow for Flatten Nested with Array.flat()
Recommendation Algorithm Flow for Flatten Nested with Array.flat()

Solution Approach

function solution(arr, depth) {
  return arr.flat(depth);
}

Best Answers

javascript - Approach 1
function solution(arr, depth) {
  return arr.flat(depth);
}