Add unionWith, unionBy
This commit is contained in:
18
snippets/unionBy.md
Normal file
18
snippets/unionBy.md
Normal file
@ -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]
|
||||||
|
```
|
||||||
16
snippets/unionWith.md
Normal file
16
snippets/unionWith.md
Normal file
@ -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]
|
||||||
|
```
|
||||||
@ -219,6 +219,8 @@ truncateString:string
|
|||||||
truthCheckCollection:object,logic,array
|
truthCheckCollection:object,logic,array
|
||||||
unescapeHTML:string,browser
|
unescapeHTML:string,browser
|
||||||
union:array,math
|
union:array,math
|
||||||
|
unionBy:array,function
|
||||||
|
unionWith:array,function
|
||||||
uniqueElements:array
|
uniqueElements:array
|
||||||
untildify:node,string
|
untildify:node,string
|
||||||
URLJoin:string,utility,regexp
|
URLJoin:string,utility,regexp
|
||||||
|
|||||||
Reference in New Issue
Block a user