Mapped array intersection
JavaScript, Array · Oct 20, 2020

Returns the elements that exist in both arrays, after applying the provided function to each array element of both.
- Create a
Set
by applyingfn
to all elements inb
. - Use
Array.prototype.filter()
ona
to only keep elements, which produce values contained inb
whenfn
is applied to them.
const intersectionBy = (a, b, fn) => { const s = new Set(b.map(fn)); return [...new Set(a)].filter(x => s.has(fn(x))); }; intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1] intersectionBy( [{ title: 'Apple' }, { title: 'Orange' }], [{ title: 'Orange' }, { title: 'Melon' }], x => x.title ); // [{ title: 'Orange' }]