🛠️ 처음부터 만드는 Flatten — 중첩 배열을 평탄화하기
깊게 중첩된 배열을 한 층으로 펴는 Flatten을 만들어봅시다.
```javascript
// 기본: 재귀로 모든 깊이 평탄화
function flatten(arr) {
return arr.reduce((flat, item) => {
return flat.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}
console.log(flatten([1, [2, [3, [4, 5]]]]));
// → [1, 2, 3, 4, 5]
```
깊이 제한 버전 — 특정 깊이까지만 펴기:
```javascript
function flattenDepth(arr, depth = 1) {
return arr.reduce((flat, item) => {
if (Array.isArray(item) && depth > 0) {
return flat.concat(flattenDepth(item, depth - 1));
}
return flat.concat(item);
}, []);
}
console.log(flattenDepth([1, [2, [3, 4]]], 1)); // → [1, 2, [3, 4]]
console.log(flattenDepth([1, [2, [3, 4]]], 2)); // → [1, 2, 3, 4]
```
모던 방식 — `Array.prototype.flat()` (ES2019):
```javascript
[1, [2, [3, 4]]].flat(); // 깊이 1
[1, [2, [3, 4]]].flat(2); // 깊이 2
[1, [2, [3, [4, [5]]]]].flat(Infinity); // 완전 평탄화
```
핵심:
`reduce()` + `concat()`로 배열 합치기
재귀로 깊은 중첩 처리
깊이 파라미터로 유연성 확보
모던 코드는 `flat()` 직접 사용 추천
실무에서는 깊이 제한이 성능상 유리합니다. 원본 배열을 수정하지 않는 불변성도 장점!
```javascript
// 기본: 재귀로 모든 깊이 평탄화
function flatten(arr) {
return arr.reduce((flat, item) => {
return flat.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}
console.log(flatten([1, [2, [3, [4, 5]]]]));
// → [1, 2, 3, 4, 5]
```
깊이 제한 버전 — 특정 깊이까지만 펴기:
```javascript
function flattenDepth(arr, depth = 1) {
return arr.reduce((flat, item) => {
if (Array.isArray(item) && depth > 0) {
return flat.concat(flattenDepth(item, depth - 1));
}
return flat.concat(item);
}, []);
}
console.log(flattenDepth([1, [2, [3, 4]]], 1)); // → [1, 2, [3, 4]]
console.log(flattenDepth([1, [2, [3, 4]]], 2)); // → [1, 2, 3, 4]
```
모던 방식 — `Array.prototype.flat()` (ES2019):
```javascript
[1, [2, [3, 4]]].flat(); // 깊이 1
[1, [2, [3, 4]]].flat(2); // 깊이 2
[1, [2, [3, [4, [5]]]]].flat(Infinity); // 완전 평탄화
```
핵심:
실무에서는 깊이 제한이 성능상 유리합니다. 원본 배열을 수정하지 않는 불변성도 장점!
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!