Skip to content

Instantly share code, notes, and snippets.

@renaudtertrais
Created July 5, 2016 13:59
Show Gist options
  • Save renaudtertrais/25fc5a2e64fe5d0e86894094c6989e10 to your computer and use it in GitHub Desktop.
Save renaudtertrais/25fc5a2e64fe5d0e86894094c6989e10 to your computer and use it in GitHub Desktop.
A simple ES6 zip function
const zip = (arr, ...arrs) => {
return arr.map((val, i) => arrs.reduce((a, arr) => [...a, arr[i]], [val]));
}
// example
const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [7, 8, 9];
zip(a, b); // [[1, 4], [2, 5], [3, 6]]
zip(a, b, c); // [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
zip.apply(null, zip(a, b)); // [[1, 2, 3], [4, 5, 6]]
@matyasfodor
Copy link

Hi, take a look at this:
https://gist.github.com/matyasfodor/9ae9ee9a6c619c6752bc686f2baabbd1
It's a bit more complex, but in your script the length of the first array defines the length of the output array. In my solution you have more control over it.

@dominikandreas
Copy link

dominikandreas commented Jun 17, 2021

here's a version that behaves more like python (length is reduced to the smallest array) and is slightly more readable:

const zip = (...arrays) => {
  const minLen = Math.min(...arrays.map(arr => arr.length));
  const [firstArr, ...restArrs] = arrays;
  return firstArr.slice(0, minLen).map(
    (val, i) => [val, ...restArrs.map( arr => arr[i]) ]
  );
}


console.log(zip([0, 1], [2, 3, 4]))  // [[0, 2], [1, 3]]
console.log(zip(...[[0, 2], [1, 3]]))  // [[0, 1], [2, 3]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment