본문 바로가기
Library & Framework/Lodash

[Lodash] 배열 차집합(difference) 구하기

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

difference

lodash에서 제공하고 있는 difference() 메서드의 경우 차집합의 개념과 마찬가지로 하나의 기준이 되는 배열이 있고 그 이후에 오는 배열로 이루어진 값들과 비교하여 중복되지 않는 값을 반환한다.

// _.difference(array, [values])

const arr = [2, 1]

console.log(_.difference(arr, [2, 3]))
// [1]
console.log(_.difference(arr, [2, 3], [1]))
// []
console.log(_.difference(arr, [3, 4], [5]))
// [2. 1]

새로운 배열을 반환하기 때문에 변수에 담아서 사용하도록 하자.

 

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

 

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


differenceBy

lodash에서 제공하고 있는 differenceBy() 메서드의 경우 다른 ~By() 메서드와 마찬가지로 기능은 difference() 메서드와 동일 하지만 기준 값을 정의할 수 있기에 단순 배열이 아니라 객체로 이루어진 배열값에 적용하기 용이하다.

// _.differenceBy(array, [values], [iteratee=_.identity])

const search1 = [
    { 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},
];

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

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

// [{ id: 19, title: 'kinvd19', name: 'han', age: 16}]

중복되는 모든 값을 제거하고 남은 하나의 값만 출력되는 것을 볼 수 있다.

 

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

 

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