본문 바로가기
Library & Framework/Lodash

[Lodash] 배열 중복 제거하기 (ft. uniq, uniqBy, union, unionBy)

by 썸머워즈 2023. 2. 22.
반응형

uniq

lodash에서 제공하고 있는 uniq() 메서드의 경우 단순하게 여러 개의 동일한 값을 가지고 있는 배열의 중복 데이터를 제거한다.

// _.uniq(array)

const arr1 = [1,1,1,3,3,4,5,2,6,4,7]
console.log(_.uniq(arr1));
// [1,3,4,5,2,6,7]

uniqBy

아마 사용하게 된다면 위에서 설명한 uniq메서드보다는 uniqBy 메서드를 좀 더 많이 사용하지 않을까 생각된다.

uniqBy() 메서드는 "중복을 구분할 속성"값을 두번째 인수로 사용이 가능하다.

// _.uniqBy(array, identity)

const search = [
    { id: 12, title: 'testest', name: 'jack', age: 26},
    { id: 15, title: 'test4', name: 'han', age: 16},
    { id: 16, title: 'test3', name: 'kim', age: 43},
    { id: 13, title: 'test2', name: 'jo', age: 46},
    { id: 12, title: 'testest', name: 'jack', age: 26},
    { id: 12, title: 'testest', name: 'jack', age: 26},
];
console.log(_.uniqBy(search, 'id'));

// [{id: 12, title: 'testest', name: 'jack', age: 26} 
// {id: 15, title: 'test4', name: 'han', age: 16}
// {id: 16, title: 'test3', name: 'kim', age: 43}
// {id: 13, title: 'test2', name: 'jo', age: 46}]

보통 개발을 하게 되면 배열안에는 객체 형식의 데이터들이 들어가 있는 경우가 많을텐데,

이때 중복을 구분할 속성을 사용하여 특정 속성을 기준으로 중복을 제거한 데이터를 만들 수 있다.


union

union은 메서드명에서 느껴지는 것 처럼 위에서 설명한 uniq와는 성격이 좀 다르다.

하지만 분명 중복을 제거할 때 상황에 따라 필요한 메서드임에는 틀림없다.

union() 메서드는 여러 배열을 합칠 때 중복을 제거하고 반환해준다.

// _.union(...arrays)

console.log(_.union([1], [1, 2], [1,2,3]));
// [1, 2, 3]

unionBy

uniqBy를 위에서 보고 왔으니 짐작이 갈 것이다.

unionBy() 메서드는 "중복을 구분할 속성"값을 사용할 수 있다.

// _.unionBy(...arrays, identity)

const search1 = [
    { id: 12, title: 'testest', name: 'jack', age: 26},
    { id: 15, title: 'test4', name: 'han', age: 16},
    { id: 16, title: 'test3', name: 'kim', age: 43},
    { id: 13, title: 'test2', name: 'jo', age: 46},
    { id: 12, title: 'testest', name: 'jack', age: 26},
    { id: 12, title: 'testest', name: 'jack', age: 26},
];

const search2 = [
    { id: 12, title: 'testest', name: 'jack', age: 26},
    { id: 15, title: 'test4', name: 'han', age: 16},
    { id: 16, title: 'test3', name: 'kim', age: 43},
    { id: 13, title: 'test2', name: 'jo', age: 46},
    { id: 12, title: 'testest', name: 'jack', age: 26},
    { id: 12, title: 'testest', name: 'jack', age: 26},
];

console.log(_.unionBy(search1, search2, 'id'));

// [{id: 12, title: 'testest', name: 'jack', age: 26} 
// {id: 15, title: 'test4', name: 'han', age: 16}
// {id: 16, title: 'test3', name: 'kim', age: 43}
// {id: 13, title: 'test2', name: 'jo', age: 46}]

 

예제를 작성하기가 귀찮아서... 위에서 사용한걸 가져왔는데 어떤식으로 동작하는지 알 수 있을거라 생각된다.


참고: https://lodash.com/docs/4.17.15

 

Lodash Documentation

_(value) source Creates a lodash object which wraps value to enable implicit method chain sequences. Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primiti

lodash.com

반응형


댓글

TOP