Zip in JavaScript

Define a funcion that zips arrays in a way similar to Python's itertools.zip_longest.

itertools.zip_longest documentation

Answer on Stack Overflow

var _zip = (arr, ...arrs) => {
  return arr.map((val, i) => arrs.reduce((a, arr) => [...a, arr[i]], [val]));
}

I made changes to make the function variadic.

In [5]:
var zip = (...[arr, ...arrs]) => {
  return arr.map((val, i) => arrs.reduce((a, arr) => [...a, arr[i] || null], [val]));
}
In [6]:
var data = [
    (_, i) => i + 65,
    (_, i) => i + 97,
    (_, i) => 33 + 15 + i,
]
    .map(f => String.fromCharCode(...Array.from({length: 26}, f)))
    .map(item => Array.from(item))
In [7]:
_zip(data[0], ...data.slice(1))
Out[7]:
[
  [ 'A', 'a', '0' ], [ 'B', 'b', '1' ],
  [ 'C', 'c', '2' ], [ 'D', 'd', '3' ],
  [ 'E', 'e', '4' ], [ 'F', 'f', '5' ],
  [ 'G', 'g', '6' ], [ 'H', 'h', '7' ],
  [ 'I', 'i', '8' ], [ 'J', 'j', '9' ],
  [ 'K', 'k', ':' ], [ 'L', 'l', ';' ],
  [ 'M', 'm', '<' ], [ 'N', 'n', '=' ],
  [ 'O', 'o', '>' ], [ 'P', 'p', '?' ],
  [ 'Q', 'q', '@' ], [ 'R', 'r', 'A' ],
  [ 'S', 's', 'B' ], [ 'T', 't', 'C' ],
  [ 'U', 'u', 'D' ], [ 'V', 'v', 'E' ],
  [ 'W', 'w', 'F' ], [ 'X', 'x', 'G' ],
  [ 'Y', 'y', 'H' ], [ 'Z', 'z', 'I' ]
]
In [12]:
zip(...data)
Out[12]:
[
  [ 'A', 'a', '0' ], [ 'B', 'b', '1' ],
  [ 'C', 'c', '2' ], [ 'D', 'd', '3' ],
  [ 'E', 'e', '4' ], [ 'F', 'f', '5' ],
  [ 'G', 'g', '6' ], [ 'H', 'h', '7' ],
  [ 'I', 'i', '8' ], [ 'J', 'j', '9' ],
  [ 'K', 'k', ':' ], [ 'L', 'l', ';' ],
  [ 'M', 'm', '<' ], [ 'N', 'n', '=' ],
  [ 'O', 'o', '>' ], [ 'P', 'p', '?' ],
  [ 'Q', 'q', '@' ], [ 'R', 'r', 'A' ],
  [ 'S', 's', 'B' ], [ 'T', 't', 'C' ],
  [ 'U', 'u', 'D' ], [ 'V', 'v', 'E' ],
  [ 'W', 'w', 'F' ], [ 'X', 'x', 'G' ],
  [ 'Y', 'y', 'H' ], [ 'Z', 'z', 'I' ]
]
In [13]:
zip(Array.from('asdf'), Array.from('tyu'))
Out[13]:
[ [ 'a', 't' ], [ 's', 'y' ], [ 'd', 'u' ], [ 'f', null ] ]