Created
July 5, 2016 13:59
-
-
Save renaudtertrais/25fc5a2e64fe5d0e86894094c6989e10 to your computer and use it in GitHub Desktop.
A simple ES6 zip function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]] | |
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
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.