Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

주니어에서 시니어로

[Javascript] 두 배열 비교 본문

STUDY/Javascript

[Javascript] 두 배열 비교

_JJ_ 2023. 4. 12. 23:49

자주 쓰이는 배열 비교에 대해서 정리해보려고 한다.


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

https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript