diff --git a/snippets/unzip.md b/snippets/unzip.md new file mode 100644 index 000000000..9c01f9285 --- /dev/null +++ b/snippets/unzip.md @@ -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]] +``` diff --git a/tag_database b/tag_database index 13ccb8adb..f774897cb 100644 --- a/tag_database +++ b/tag_database @@ -223,6 +223,7 @@ unionBy:array,function unionWith:array,function uniqueElements:array untildify:node,string +unzip:array URLJoin:string,utility,regexp UUIDGeneratorBrowser:browser,utility,random UUIDGeneratorNode:node,utility,random