Helloworld!/Javascript & jQuery
[Javascript] 교집합, 차집합, 배타적논리합
shaking
2019. 6. 27. 13:23
다음과 같이 두개의 배열이 있었을 때
let arr1 = [1, 2, 3];
let arr2 = [2, 3, 4, 5];
두 배열의 값들을 비교하여 합, 교, 차의 값을 구하고 싶다면 다음과 같다.
1. 차집합
let difference = arr1.filter(x => !arr2.includes(x)); // 결과 1
2. 교집합
let difference = arr1.filter(x => arr2.includes(x)); // 결과 2, 3
3. 배타적논리합
let difference = arr1
.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x))); // 결과 1, 4, 5
How to get the difference between two arrays in Javascript?
Is there a way to return the difference between two arrays in JavaScript? For example: var a1 = ['a', 'b']; var a2 = ['a', 'b', 'c', 'd']; // need ["c", "d"] Any advice greatly appreciated.
stackoverflow.com