주니어에서 시니어로
[Javascript] 두 배열 비교 본문
자주 쓰이는 배열 비교에 대해서 정리해보려고 한다.
1. 비교 (Compare)
const a1 = ['a', 'b', 'c', 'd'];
const a2 = ['a', 'b'];
// 비교
console.log( JSON.stringify(a1) === JSON.stringify(a2)) // false
2. 교집합 (Intersection)
const a1 = ['a', 'b', 'c', 'd'];
const a2 = ['a', 'b'];
// 교집합
let intersection = a1.filter(x => a2.includes(x)) // ['a', 'b']
3. 차집합(Difference)
const a1 = ['a', 'b', 'c', 'd'];
const a2 = ['a', 'b'];
// 차집합
let difference = a1.filter(x => !a2.includes(x)) // ['c', 'd']
4. 대칭차집합(Symmetric Difference)
두 배열을 비교하여 각 배열 안 공통 원소의 나머지 것들을 구하는 방식이다.
const a1 = ['a', 'b', 'c', 'd'];
const a2 = ['a', 'e', 'f', 'g'];
// 대칭 차집합
let difference = a1.filter(x => !a2.includes(x))
.concat(a2.filter(x => !a1.includes(x))) // ['b', 'c', 'd', 'e', 'f', 'g']
이렇게 하면 a2에 없는 a1의 모든 요소를 포함하는 배열을 얻을 수 있으며, 그 반대의 경우도 마찬가지이다.
reference
'STUDY > Javascript' 카테고리의 다른 글
[Javascript] readline (0) | 2023.05.02 |
---|---|
가비지 컬렉션 (Garbage Collection) 이란? (0) | 2023.04.18 |
[HTML/Javascript] 오디오 재생 (0) | 2023.04.14 |
스코프(Scope) (0) | 2023.04.07 |
JavaScript 작동 방식: 엔진, 런타임 및 호출 스택 (0) | 2023.03.20 |