🛠️ 처음부터 만드는 Flatten — 중첩 배열을 평탄화하기
배열이 여러 층으로 중첩되어 있을 때 한 차원 낮춘다면? `[1, [2, [3, 4]]]` → `[1, 2, 3, 4]`
```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
flatten([1, [2, 3], [[4, 5]]]);
// → [1, 2, 3, [4, 5]]
flatten([1, [2, [3, [4]]]], 2);
// → [1, 2, 3, [4]]
flatten([1, [2, [3, [4]]]], Infinity);
// → [1, 2, 3, 4]
```
```typescript
function flatten(arr: T[], depth: number = Infinity): T[] {
// 위와 동일하되 재귀 호출 시 타입 안전성 유지
const result: T[] = [];
for (const item of arr) {
if (Array.isArray(item) && depth > 0) {
result.push(...flatten(item as T[], depth - 1));
} else {
result.push(item);
}
}
return result;
}
```
JSON 파싱 결과 정리할 때 유용
API 응답에서 중첩된 리스트 병합
`depth` 파라미터로 얼마나 깊이 파고들지 제어
ES2019 이후 네이티브 `Array.prototype.flat()` 지원: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
기본 구현
```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
flatten([1, [2, 3], [[4, 5]]]);
// → [1, 2, 3, [4, 5]]
flatten([1, [2, [3, [4]]]], 2);
// → [1, 2, 3, [4]]
flatten([1, [2, [3, [4]]]], Infinity);
// → [1, 2, 3, 4]
```
TypeScript 버전
```typescript
function flatten
// 위와 동일하되 재귀 호출 시 타입 안전성 유지
const result: T[] = [];
for (const item of arr) {
if (Array.isArray(item) && depth > 0) {
result.push(...flatten(item as T[], depth - 1));
} else {
result.push(item);
}
}
return result;
}
```
실전 팁
ES2019 이후 네이티브 `Array.prototype.flat()` 지원: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!