Flatten Array
Flatten Array - Explanation
Problem Summary
Write a function that flattens a nested array one level deep.
Go to Problem →Detailed Explanation
이 문제는 **배열 평탄화(flattening)**의 개념과 **flat() 메서드**를 학습합니다. **배열 평탄화란?** 중첩된 배열을 단일 레벨의 배열로 변환하는 것입니다: [[1, 2], [3, 4]] → [1, 2, 3, 4] **flat() 메서드** ES2019에 추가된 flat()은 배열을 평탄화합니다: - `arr.flat()` - 1단계 평탄화 (기본값) - `arr.flat(2)` - 2단계 평탄화 - `arr.flat(Infinity)` - 완전 평탄화 **[[1, 2], [3, 4], [5]] 처리** flat()은 각 내부 배열의 요소를 꺼내 하나의 배열로 합칩니다: [[1, 2], [3, 4], [5]] → [1, 2, 3, 4, 5] **reduce로 구현하기** ```javascript function flatten(arr) { return arr.reduce((flat, current) => flat.concat(current), []); } ``` **concat의 특성** concat은 배열이면 요소를 펼쳐서 합치고, 배열이 아니면 그대로 추가합니다: - [].concat([1, 2]) → [1, 2] - [].concat(1) → [1] **스프레드 연산자 방법** `[].concat(...arr)` 또는 `[...arr[0], ...arr[1], ...]`처럼 스프레드로도 가능하지만, flat()이 가장 간결합니다.
Solution Code
function flatten(arr) {
return arr.flat();
}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