💻 Dev

🛠️ 처음부터 만드는 Zip — 여러 배열을 짝지어서 합치기

# Zip — 여러 배열을 짝지어서 합치기

문제 상황


여러 배열이 있을 때, 같은 인덱스의 요소들을 모아서 새 배열을 만들고 싶다면?
```javascript
const names = ['Alice', 'Bob', 'Charlie'];
const ages = [25, 30, 35];
const cities = ['Seoul', 'Busan', 'Daegu'];
// 원하는 결과:
// [['Alice', 25, 'Seoul'], ['Bob', 30, 'Busan'], ['Charlie', 35, 'Daegu']]
```

구현


```javascript
function zip(...arrays) {
if (arrays.length === 0) return [];

const minLength = Math.min(...arrays.map(arr => arr.length));
const result = [];

for (let i = 0; i < minLength; i++) {
result.push(arrays.map(arr => arr[i]));
}

return result;
}
```

사용 예제


```javascript
const names = ['Alice', 'Bob', 'Charlie'];
const ages = [25, 30, 35];
console.log(zip(names, ages));
// [['Alice', 25], ['Bob', 30], ['Charlie', 35]]
// 배열 길이가 다를 때는 짧은 배열 기준
console.log(zip([1, 2, 3], ['a', 'b']));
// [[1, 'a'], [2, 'b']]
```

핵심 아이디어


1. 최소 길이 찾기: 가장 짧은 배열의 길이를 구한다
2. 인덱스로 순회: 0부터 최소 길이까지 반복
3. 같은 인덱스 모으기: 모든 배열의 i번째 요소를 모은다

응용: 키-값 쌍을 객체로


```javascript
const keys = ['name', 'age', 'city'];
const values = ['Alice', 25, 'Seoul'];
const result = Object.fromEntries(zip(keys, values));
// { name: 'Alice', age: 25, city: 'Seoul' }
```
Zip은 Chunk, Flatten과 함께 배열 조작의 기본 도구입니다. 함수형 프로그래밍에서 자주 사용되는 패턴이죠!
💬 0
👁 0 views

Comments (0)

💬

No comments yet.

Be the first to comment!