Add unzipWith
This commit is contained in:
23
snippets/unzipWith.md
Normal file
23
snippets/unzipWith.md
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
### unzipWith
|
||||||
|
|
||||||
|
Creates an array of elements, ungrouping the elements in an array produced by [zip](#zip) and applying the provided function.
|
||||||
|
|
||||||
|
Use `Math.max.apply()` to get the longest subarray in the array, `Array.map()` to make each element an array.
|
||||||
|
Use `Array.reduce()` and `Array.forEach()` to map grouped values to individual arrays.
|
||||||
|
Use `Array.map()` and the spread operator (`...`) to apply `fn` to each individual group of elements.
|
||||||
|
|
||||||
|
```js
|
||||||
|
const unzipWith = (arr, fn) =>
|
||||||
|
arr
|
||||||
|
.reduce(
|
||||||
|
(acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
|
||||||
|
Array.from({
|
||||||
|
length: Math.max(...arr.map(x => x.length)),
|
||||||
|
}).map(x => [])
|
||||||
|
)
|
||||||
|
.map(val => fn(...val));
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)); // [3, 30, 300]
|
||||||
|
```
|
||||||
@ -224,6 +224,7 @@ unionWith:array,function
|
|||||||
uniqueElements:array
|
uniqueElements:array
|
||||||
untildify:node,string
|
untildify:node,string
|
||||||
unzip:array
|
unzip:array
|
||||||
|
unzipWith:array,function,advanced
|
||||||
URLJoin:string,utility,regexp
|
URLJoin:string,utility,regexp
|
||||||
UUIDGeneratorBrowser:browser,utility,random
|
UUIDGeneratorBrowser:browser,utility,random
|
||||||
UUIDGeneratorNode:node,utility,random
|
UUIDGeneratorNode:node,utility,random
|
||||||
|
|||||||
Reference in New Issue
Block a user