diff --git a/snippets/intersectionBy.md b/snippets/intersectionBy.md new file mode 100644 index 000000000..3f28a78be --- /dev/null +++ b/snippets/intersectionBy.md @@ -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] +``` diff --git a/snippets/intersectionWith.md b/snippets/intersectionWith.md new file mode 100644 index 000000000..ae5483c47 --- /dev/null +++ b/snippets/intersectionWith.md @@ -0,0 +1,14 @@ +### intersectionWith + +Returns a list of elements that exist in both arrays, using a provided comparator function. + +Use `Array.filter()` and `Array.findIndex()` in combination with the provided comparator to determine intersecting values. + +```js +const intersectionWith = (a, b, comp) => + a.filter(x => b.findIndex(y => comp(x, y)) !== -1); +``` + +```js +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] +``` diff --git a/tag_database b/tag_database index a4eac6748..78f14816c 100644 --- a/tag_database +++ b/tag_database @@ -91,6 +91,8 @@ initializeArrayWithRangeRight:array,math initializeArrayWithValues:array,math inRange:math intersection:array,math +intersectionBy:array,function +intersectionWith:array,function invertKeyValues:object,function is:type,array,regexp isAbsoluteURL:string,utility,browser,url