Skip to content

Instantly share code, notes, and snippets.

@BolajiAyodeji
Created August 25, 2021 06:35
Show Gist options
  • Save BolajiAyodeji/90fcab8d5ace7b742148feebef8492be to your computer and use it in GitHub Desktop.
Save BolajiAyodeji/90fcab8d5ace7b742148feebef8492be to your computer and use it in GitHub Desktop.
Find duplicate emails (or any data type) in an array and the intersection, difference, symmetrical difference, and union of two arrays.
const dataA = []
const dataB = []
const arrA = dataA.map(e => e.toLowerCase().replace(/\s/g, ''));
const arrB = dataB.map(e => e.toLowerCase().replace(/\s/g, ''));
console.log(arrA.length, arrB.length)
// Find duplicates in array A
let duplicatesA = []
const tempArray = [...arrA].sort()
for (let i = 0; i < tempArray.length; i++) {
if (tempArray[i + 1] === tempArray[i]) {
duplicatesA.push(tempArray[i])
}
}
console.log(duplicatesA, duplicatesA.length);
// Find duplicates in array B
let duplicatesB = []
const tempArray = [...arrB].sort()
for (let i = 0; i < tempArray.length; i++) {
if (tempArray[i + 1] === tempArray[i]) {
duplicatesB.push(tempArray[i])
}
}
console.log(duplicatesB, duplicatesB.length);
// Array intersection
let intersection = arrA.filter(x => arrB.includes(x));
console.log(intersection, intersection.length);
// Array difference (in A and not in B)
let difference1 = arrA.filter(x => !arrB.includes(x));
console.log(difference1, difference1.length);
// Array difference (in B and not in A)
let difference2 = arrB.filter(x => !arrA.includes(x));
console.log(difference2, difference2.length);
// Array symetrical difference
let difference3 = arrA
.filter(x => !arrB.includes(x))
.concat(arrB.filter(x => !arrA.includes(x)));
console.log(difference3, difference3.length);
// Array union
let union = arrA.concat(arrB);
console.log(union, union.length);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment