Flatten Deep
Flatten Deep - Explanation
Problem Summary
Write a function that flattens a nested array to any depth.
Go to Problem →Detailed Explanation
이 문제는 **재귀와 Array.isArray**를 사용하여 중첩 배열을 완전히 평탄화하는 방법을 학습합니다. ## 핵심 개념: 깊은 평탄화 모든 중첩 수준을 재귀적으로 평탄화합니다. ### 구현 ```javascript function flattenDeep(arr) { return arr.reduce((flat, item) => flat.concat(Array.isArray(item) ? flattenDeep(item) : item), []); } ``` ### 동작 원리 1. 각 요소가 배열인지 확인 2. 배열이면 재귀 호출 3. 아니면 그대로 추가 ### 실행 예시 ```javascript [1, [2, [3, [4]]]] → [1, ...flattenDeep([2, [3, [4]]])] → [1, 2, ...flattenDeep([3, [4]])] → [1, 2, 3, ...flattenDeep([4])] → [1, 2, 3, 4] ``` ### 대안: flat(Infinity) ```javascript arr.flat(Infinity) ``` ES2019 이상에서 사용 가능합니다. ### 스택 오버플로우 주의 매우 깊은 중첩에서는 스택 오버플로우가 발생할 수 있습니다.
Solution Code
function flattenDeep(arr) {
return arr.reduce((flat, item) =>
flat.concat(Array.isArray(item) ? flattenDeep(item) : item), []);
}Key Concepts from This Problem
Common Mistakes
Hints
Complexity Analysis
Time Complexity
O(n)
Grows linearly with input size
Space Complexity
O(n)
Uses memory proportional to input size