diff --git a/snippets/unionBy.md b/snippets/unionBy.md new file mode 100644 index 000000000..3680c6d1c --- /dev/null +++ b/snippets/unionBy.md @@ -0,0 +1,18 @@ +### unionBy + +Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both. + +Create a `Set` by applying all `fn` to all values of `a`. +Create a `Set` from `a` and all elements in `b` whose value, after applying `fn` does not match a value in the previously created set. +Return the last set converted to an array. + +```js +const unionBy = (a, b, fn) => { + const s = new Set(a.map(v => fn(v))); + return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))])); +}; +``` + +```js +unionBy([2.1], [1.2, 2.3], Math.floor); // [2.1, 1.2] +``` diff --git a/snippets/unionWith.md b/snippets/unionWith.md new file mode 100644 index 000000000..dbfee938b --- /dev/null +++ b/snippets/unionWith.md @@ -0,0 +1,16 @@ +### unionWith + +Returns every element that exists in any of the two arrays once, using a provided comparator function. + +Create a `Set` with all values of `a` and values in `b` for which the comparator finds no matches in `a`, using `Array.findIndex()`. + +```js +const unionWith = (a, b, comp) => + Array.from( + new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)]) + ); +``` + +```js +unionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2, 1.5, 3, 0, 3.9] +``` diff --git a/tag_database b/tag_database index 58c4f00fc..13ccb8adb 100644 --- a/tag_database +++ b/tag_database @@ -219,6 +219,8 @@ truncateString:string truthCheckCollection:object,logic,array unescapeHTML:string,browser union:array,math +unionBy:array,function +unionWith:array,function uniqueElements:array untildify:node,string URLJoin:string,utility,regexp