Add unzip

This commit is contained in:
Angelos Chalaris
2018-01-24 12:35:25 +02:00
parent 56d84c429e
commit 6f7878d4be
2 changed files with 22 additions and 0 deletions

21
snippets/unzip.md Normal file
View File

@ -0,0 +1,21 @@
### unzip
Creates an array of arrays, ungrouping the elements in an array produced by [zip](#zip).
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.
```js
const unzip = arr =>
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 => [])
);
```
```js
unzip([['a', 1, true], ['b', 2, false]]); //[['a', 'b'], [1, 2], [true, false]]
unzip([['a', 1, true], ['b', 2]]); //[['a', 'b'], [1, 2], [true]]
```