🛠️ 처음부터 만드는 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
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
Comments (0)
💬
No comments yet.
Be the first to comment!