From ffb917e72dbbffb983e7745c137e800d290a95b9 Mon Sep 17 00:00:00 2001 From: taltmann42 Date: Thu, 14 Dec 2017 23:54:55 +0100 Subject: [PATCH] Array zip Zip method from https://lodash.com/docs/4.17.4#zip --- snippets/array-zip.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 snippets/array-zip.md diff --git a/snippets/array-zip.md b/snippets/array-zip.md new file mode 100644 index 000000000..d63f79b15 --- /dev/null +++ b/snippets/array-zip.md @@ -0,0 +1,17 @@ +### Array zip + +Use `Math.max.apply` to get the longest array in the arguments. +Creates an array with that length as return value and use `Array.from` with a map-function to create an array of grouped elements. +If lengths of the argument-arrays vary, `undefined` is used where no value could be found. + +```js +const zip = (...arrays) => { + const maxLength = Math.max.apply(null, arrays.map(a => a.length)); + return Array.from({length: maxLength}).map((_, i) => { + return Array.from({length: arrays.length}, (_, k) => arrays[k][i]) + }) +} + +//zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]] +zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]] +```