📚

Flatten Array

Flatten Array - Explanation

보통 배열 O(n) O(n)

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

solution.js
function flatten(arr) {
  return arr.flat();
}

Key Concepts from This Problem

1. flat() 메서드
2. 배열 평탄화
3. concat 메서드
4. reduce 활용

Common Mistakes

flat()은 기본적으로 1단계만 평탄화합니다
구형 브라우저에서는 flat()이 지원되지 않을 수 있습니다
중첩 깊이가 다양하면 Infinity를 사용해야 완전 평탄화됩니다

Hints

Hint 1: flat() 메서드를 사용하거나 reduce로 구현하세요.

Complexity Analysis

Time Complexity

O(n)

Grows linearly with input size

Space Complexity

O(n)

Uses memory proportional to input size

Related Tags

#배열 #flat #중첩