const intersection = (a, b) => {
const s = new Set(b);
return […new Set(a)].filter(x => s.has(x));
};
const intersectionWith = (a, b, comp) =>
a.filter(x => b.findIndex(y => comp(x, y)) !== -1);
const intersectionBy = (a, b, fn) => {
const s = new Set(b.map(fn));
return […new Set(a)].filter(x => s.has(fn(x)));
};
intersection([1, 2, 3], [4, 3, 2]); // [2, 3]
intersectionWith(
[1, 1.2, 1.5, 3, 0],
[1.9, 3, 0, 3.9],
(a, b) => Math.round(a) === Math.round(b)
); // [1.5, 3, 0]
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' }]
Массивы и объекты JavaScript
JavaScript