Files
30-seconds-of-code/snippets/unzipWith.md
Mathias Bynens 8ee50178f3 Avoid confusing prototype methods for static methods
Correct: `Array.from()` (it’s a static method)
Incorrect: `Array.join()` (doesn’t exist; it’s a prototype method)

This patch uses the common `#` syntax to denote `.prototype.`.
2018-09-28 15:44:12 -04:00

24 lines
854 B
Markdown

### 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.prototype.map()` to make each element an array.
Use `Array.prototype.reduce()` and `Array.prototype.forEach()` to map grouped values to individual arrays.
Use `Array.prototype.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]
```