Flatten Nested with Array.flat()
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
Depth 0: no flattening
Empty array
Depth 1: only first level flattened
Infinity depth: all levels
Depth 2: fully flattened
Algorithm Flow

Solution Approach
Best Answers
function solution(arr, depth) {
return arr.flat(depth);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
