From 541103321a9c908edc12d76c2dc300b8ac972e3b Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Wed, 24 Jan 2018 11:49:03 +0200 Subject: [PATCH] Add differenceBy --- snippets/differenceBy.md | 17 +++++++++++++++++ tag_database | 1 + 2 files changed, 18 insertions(+) create mode 100644 snippets/differenceBy.md diff --git a/snippets/differenceBy.md b/snippets/differenceBy.md new file mode 100644 index 000000000..626ba7cdc --- /dev/null +++ b/snippets/differenceBy.md @@ -0,0 +1,17 @@ +### differenceBy + +Returns the difference between two arrays, after applying the provided function to each array element of both. + +Create a `Set` by applying `fn` to each element in `b`, then use `Array.filter()` in combination with `fn` on `a` to only keep values not contained in the previously created set. + +```js +const differenceBy = (a, b, fn) => { + const s = new Set(b.map(v => fn(v))); + return a.filter(x => !s.has(fn(x))); +}; +``` + +```js +differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2] +differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ] +``` diff --git a/tag_database b/tag_database index b8afea8ab..231cf9379 100644 --- a/tag_database +++ b/tag_database @@ -35,6 +35,7 @@ defaults:object defer:function detectDeviceType:browser difference:array,math +differenceBy:array,function differenceWith:array,function digitize:math,array distance:math