두 배열안의 객체 비교후 중복값 제거

louis220·2022년 6월 21일
0

두개의 배열을 비교하여 같은 b의 id와 같은 값이 a에 있다면 a에서 그값을 제거하는 방법

const a = [{id: 1, name: 'Tom'}, {id: 2, name: 'Jack'}]
const b = [{id: 3, name: 'Red'}, {id: 1, name: 'Tim'}]
const result = a.filter(item => {
	return !b.some(other => other.id === item.id)
}
console.log(result) => [{id: 2, name: 'Jack'}]
// 만약 name까지 같이 비교하고 싶다면 
	return !b.some(other => other.id === item.id
    && other.name === item.name) 을 해주면 된다.

응용해 두 배열을 비교해 같지 않은 것만 걸러내고 싶다면

return !b.some 이 아닌 b.some(...) 으로 걸러내면 되겠다.

참고
https://stackoverflow.com/questions/65289444/javascript-two-array-in-object-deduplication

profile
기록을 하자

0개의 댓글