Skip to content

Instantly share code, notes, and snippets.

@oshinko
Created June 30, 2021 03:53
Show Gist options
  • Save oshinko/bee28689426fad97bfddad08707535d1 to your computer and use it in GitHub Desktop.
Save oshinko/bee28689426fad97bfddad08707535d1 to your computer and use it in GitHub Desktop.
How to zip arrays with JavaScript.
/**
* const expected = [[0, 2], [1, 3]]
* const actual = [...zip([0, 1], [2, 3])]
* assert JSON.stringify(expected) === JSON.stringify(actual)
*/
export function *zip(...arrays) {
try {
arrays[0] = [...arrays[0]]
} catch {
throw Error(`TypeError: First argument "${arrays[0]}" is not iterable`)
}
for (const i in arrays[0])
yield arrays.map(array => array[i])
}
export default {
zip
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment