Add intersectionBy, intersectionWith

This commit is contained in:
Angelos Chalaris
2018-01-24 12:53:18 +02:00
parent 8303109529
commit 4ed97c92e3
3 changed files with 32 additions and 0 deletions

View File

@ -0,0 +1,16 @@
### intersectionBy
Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.
Create a `Set` by applying `fn` to all elements in `b`, then use `Array.filter()` on `a` to only keep elements, which produce values contained in `b` when `fn` is applied to them.
```js
const intersectionBy = (a, b, fn) => {
const s = new Set(b.map(x => fn(x)));
return a.filter(x => s.has(fn(x)));
};
```
```js
intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]
```