🛠️ 처음부터 만드는 Uniq — 배열에서 중복 제거하기
문제: 배열에서 중복값을 깔끔하게 제거하고 싶다
```javascript
const numbers = [1, 2, 2, 3, 3, 3, 4];
// [1, 2, 3, 4]로 만들고 싶은데...
```
해결: Uniq 함수 만들기
기본 구현 — Set 활용
```javascript
function uniq(arr) {
return [...new Set(arr)];
}
const numbers = [1, 2, 2, 3, 3, 3, 4];
console.log(uniq(numbers)); // [1, 2, 3, 4]
const words = ['apple', 'apple', 'banana', 'cherry', 'banana'];
console.log(uniq(words)); // ['apple', 'banana', 'cherry']
```
심화 — 커스텀 비교 함수
```javascript
function uniqBy(arr, compareFn) {
const seen = [];
return arr.filter(item => {
const isDuplicate = seen.some(seenItem => compareFn(item, seenItem));
if (!isDuplicate) seen.push(item);
return !isDuplicate;
});
}
// 객체 배열에서 id 기준 중복 제거
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alice2' },
];
const uniqueUsers = uniqBy(users, (a, b) => a.id === b.id);
console.log(uniqueUsers);
// [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
```
프로덕션 레벨 — Lodash 스타일
```javascript
function uniqBy(arr, iteratee) {
const seen = new Map();
return arr.filter(item => {
const key = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];
if (seen.has(key)) return false;
seen.set(key, true);
return true;
});
}
// 사용 예
const products = [
{ id: 1, name: 'Laptop', category: 'Electronics' },
{ id: 2, name: 'Mouse', category: 'Electronics' },
{ id: 3, name: 'Desk', category: 'Furniture' },
{ id: 1, name: 'Laptop V2', category: 'Electronics' },
];
const unique = uniqBy(products, 'id');
console.log(unique.length); // 3
// 함수로도 가능
const uniqueByCategory = uniqBy(products, p => p.category);
console.log(uniqueByCategory.length); // 2
```
핵심 설명
기본형 (Set)
uniqBy 함수
실전 팁
```typescript
function uniqBy
const seen = new Set
return arr.filter(item => {
if (seen.has(item[key])) return false;
seen.add(item[key]);
return true;
});
}
```
참고
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!