💻 Dev

🛠️ 처음부터 만드는 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)
  • ✅ 원시값(숫자, 문자열)에는 최고로 빠름

  • ✅ 코드가 매우 간결함

  • ❌ 객체 비교가 참조 기반 (같은 내용이어도 다른 객체면 중복 제거 X)

  • uniqBy 함수
  • ✅ 복잡한 객체 비교 가능 (id, email, name 등)

  • ✅ 커스텀 로직 주입 가능

  • 💡 Map을 쓰면 O(n) 성능, filter + some은 O(n²)

  • 실전 팁
  • 큰 배열: Map 버전 사용 (성능 우선)

  • 작은 배열 + 단순 타입: Set 버전 (코드 간결)

  • TypeScript: 제네릭으로 타입 안전하게

  • ```typescript
    function uniqBy(arr: T[], key: keyof T): T[] {
    const seen = new Set();
    return arr.filter(item => {
    if (seen.has(item[key])) return false;
    seen.add(item[key]);
    return true;
    });
    }
    ```

    참고


  • [MDN Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)

  • [Lodash uniq](https://lodash.com/docs/#uniq)

  • [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
  • 💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!