function getIntersection(...listOfArrays) {
function getIntersectionOfTwo(intersection, iterableItem) {
// in order to compare huge arrays more efficiently access ...
const [
comparisonBase, // ... the shorter one as comparison base
comparisonList, // ... and the longer one to filter from.
] = [intersection, iterableItem]
.sort((a, b) => a.length - b.length);
// create a `Map` based lookup table from the shorter array.
const itemLookup = comparisonBase
.reduce((map, item) => map.set(item, true), new Map)
// the intersection is the result of following filter task.
return comparisonList.filter(item => itemLookup.has(item));
}
// assure only array type arguments.
listOfArrays = listOfArrays.filter(Array.isArray);
return (listOfArrays[1] ?? listOfArrays[0])
&& listOfArrays.reduce(getIntersectionOfTwo);
}
console.log(
'getIntersection() ...',
getIntersection()
);
console.log(
'getIntersection(9, "foo", 0) ...',
getIntersection(9, "foo", 0)
);
console.log(
'getIntersection([2, 7, 0], "bar") ...',
getIntersection([2, 7, 0], "bar")
);
console.log(
'getIntersection([2, 7, 0, 4], [6, 2, 7, 3]) ...',
getIntersection([2, 7, 0, 4], [6, 2, 7, 3])
);
console.log(
'getIntersection([2, 7, 0, 4], [6, 2, 7, 3], [9, 1, 2]) ...',
getIntersection([2, 7, 0, 4], [6, 2, 7, 3], [9, 1, 2])
);
console.log(
'getIntersection([2, 7, 0, 4], [6, 2, 7, 3], [9]) ...',
getIntersection([2, 7, 0, 4], [6, 2, 7, 3], [9])
);
.as-console-wrapper { min-height: 100%!important; top: 0; }