본문 바로가기
Library & Framework/Lodash

[Lodash] 배열 교집합(intersection) 구하기

by 썸머워즈 2023. 3. 8.
반응형

intersection

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

// _.intersection([arrays])

const arr1 = [1, 2, 3, 4, 5]
const arr2 = [3, 4, 5, 6, 7]

console.log(_.intersection(arr1, arr2))
// [3, 4, 5]

여기서 결과값의 순서와 참조는 첫 번째 배열에 의해 결정된다는 것만 알고 가면 될 듯하다.

 

 

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

 

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


intersectionBy

lodash에서 제공하고 있는 intersectionBy() 메서드의 경우 다른 ~By() 메서드와 마찬가지로 중복을 제거할 기준 값을 정의할 수 있다.

// _.intersectionBy(...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: 'errr', name: 'jack', age: 26},
    { id: 12, title: 'esadf', name: 'jack', age: 26},
];

const search2 = [
    { id: 12, title: 'asdaw', name: 'jack', age: 26},
    { id: 19, title: 'kinvd19', name: 'han', age: 16},
    { id: 16, title: 'test3', name: 'kim', age: 43},
    { id: 12, title: 'vaewwv', name: 'jack', age: 26},
];

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

// [{id: 12, title: 'testest', name: 'jack', age: 26} 
// {id: 16, title: 'test3', name: 'kim', age: 43}]

이 글 이전에 작성한 중복을 제거할 때 사용되던 unionBy와 마찬가지로 중복을 제거한다는 점에서는 비슷하게 보인다.

그리고 다른 메서드와 마찬가지로 항상 순서와 참조는 앞선 배열에 영향을 받는다는 점 꼭 기억해두자.

 

위 예제에서 id가 아무리 같다해도 뒤에 값들이 다를 수 있는데,
결국에 출력되는 값은 첫번째 배열의 가장 먼저 들어온 값인 것을 볼 수 있다.

 

 

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

 

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