Returns the elements that exist in both arrays, after applying the provided function to each array element of both.
Set
by applying fn
to all elements in b
.Array.prototype.filter()
on a
to only keep elements, which produce values contained in b
when fn
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' }]
Would you like to help us improve 30 seconds of code?Take a quick survey
JavaScript, Array
Returns every element that exists in any of the two arrays at least once, after applying the provided function to each array element of both.
JavaScript, Array
Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.
JavaScript, Array
Returns the difference between two arrays, after applying the provided function to each array element of both.