Created
November 13, 2019 08:43
-
-
Save timotgl/b886a6763ced6d0890a9b4ceb437fc6c to your computer and use it in GitHub Desktop.
Compare two arrays (intersection, difference)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arr1 = ["100730651975","100727767835","100731535949","100734119022","100731395492","100730978223","100723043671","100729513754","100731428590","100730087084","100731202777","100730337035","100731122761","100730787720","100730178609","100734126093","100731453507","100730654591","100730236974","100734127056"]; | |
const arr2 = ["100730178609", "100730654591", "100730651975", "100730087084", "100727767835", "100731535949", "100731395492", "100723043671", "100730978223", "100729513754", "100731202777", "100731428590", "100731122761", "100730787720", "100731453507", "100730236974", "100734127056"]; | |
const compareArrays = (a, b) => { | |
const setOfA = new Set(a); | |
const setOfB = new Set(b); | |
const intersection = new Set(); // elements in both A and B | |
const differenceB = new Set(); // elements in B but not in A | |
const differenceA = new Set(); // elements in A but not in B | |
const length = Math.max(a.length, b.length); | |
let elemOfA, elemOfB; | |
Array.from(Array(length).keys()).forEach((index) => { | |
elemOfA = a[index]; | |
elemOfB = b[index]; | |
if (elemOfA) { | |
if (setOfB.has(elemOfA)) { | |
intersection.add(elemOfA); | |
} else { | |
differenceA.add(elemOfA); | |
} | |
} | |
if (elemOfB) { | |
if (setOfA.has(elemOfB)) { | |
intersection.add(elemOfB); | |
} else { | |
differenceB.add(elemOfB); | |
} | |
} | |
}); | |
console.log('Intersection:', Array.from(intersection)); | |
console.log('Elements in B but not in A:', Array.from(differenceB)); | |
console.log('Elements in A but not in B:', Array.from(differenceA)); | |
}; | |
compareArrays(arr1, arr2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment