💻 Dev

🛠️ 처음부터 만드는 Flatten — 중첩 배열을 평탄화하기

배열이 배열을 담고 있을 때, 모든 요소를 한 단계로 펼쳐야 할 때가 있습니다.

기본 구현


```javascript
function flatten(arr, depth = Infinity) {
const result = [];

for (const item of arr) {
if (Array.isArray(item) && depth > 0) {
// 재귀적으로 펼치기
result.push(...flatten(item, depth - 1));
} else {
result.push(item);
}
}

return result;
}
```

사용 예제


```javascript
const nested = [1, [2, [3, [4, 5]]]];
flatten(nested); // [1, 2, 3, 4, 5]
flatten(nested, 1); // [1, 2, [3, [4, 5]]]
flatten(nested, 2); // [1, 2, 3, [4, 5]]
const mixed = [1, ['a', 'b'], [2, [3, 'c']]];
flatten(mixed); // [1, 'a', 'b', 2, 3, 'c']
```

핵심 포인트


  • 깊이 조절: `depth` 파라미터로 펼칠 깊이 제한

  • 재귀: 배열을 만나면 자신을 다시 호출

  • 스프레드 연산자: `...`로 펼친 배열 요소를 추가

  • 공식 대안


    ES2019+ 환경에서는 `Array.prototype.flat(depth)` 사용 가능:
    ```javascript
    [1, [2, [3, [4]]]].flat(); // [1, 2, [3, [4]]]
    [1, [2, [3, [4]]]].flat(2); // [1, 2, 3, [4]]
    [1, [2, [3, [4]]]].flat(Infinity); // [1, 2, 3, 4]
    ```
    깊이 제한이 필요 없으면 `flat()`을 추천하지만, 커스텀 로직이 필요하면 직접 구현하세요.
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!