Return the values that appear in both arrays (e.g. [1,2,3] and [2,3,4] -> [2,3]).
Put one array into a Set for O(1) lookups, then filter the other array by membership. Wrap in a Set again if you must dedupe the result.
function intersection(a, b) {
const setB = new Set(b);
return [...new Set(a)].filter((x) => setB.has(x));
}Intersection compares expected vs actual result sets in tests, or finds users who belong to two cohorts for a targeted check.
a.filter(x => b.includes(x)) is correct but times out on two 50k-element arrays. Why, and what is the fix?