Last active
February 8, 2024 08:26
-
-
Save jonschlinkert/2c5e5cd8c3a561616e8572dd95ae15e3 to your computer and use it in GitHub Desktop.
versatile JavaScript "zip" function. Works with objects, arrays, and yep - even strings.
This file contains hidden or 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
function zip(a, b) { | |
var arr = []; | |
for (var key in a) arr.push([a[key], b[key]]); | |
return arr; | |
} | |
console.log(zip('foo', 'bar')); | |
//=> [ [ 'f', 'b' ], [ 'o', 'a' ], [ 'o', 'r' ] ] | |
console.log(zip(['a', 'b', 'c'], ['x', 'y', 'z'])); | |
//=> [ [ 'a', 'x' ], [ 'b', 'y' ], [ 'c', 'z' ] ] | |
var obj1 = {a: 'aaa', b: 'bbb', c: 'ccc'}; | |
var obj2 = {a: 'xxx', b: 'yyy', c: 'zzz'}; | |
var obj3 = {x: 'xxx', y: 'yyy', z: 'zzz'}; | |
console.log(zip(obj1, obj2)); | |
//=> [ [ 'aaa', 'xxx' ], [ 'bbb', 'yyy' ], [ 'ccc', 'zzz' ] ] | |
console.log(zip(Object.keys(obj1), Object.keys(obj3))); | |
//=> [ [ 'a', 'x' ], [ 'b', 'y' ], [ 'c', 'z' ] ] |
The solution by @brokenpylons is nice, but if I am not mistaken it will run endlessly when called with an empty set of arguments?
current.some(…)
on an empty array always returns false, hence the break condition is never reached on args === []
It should be solvable by
while(iterators.length) {…}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using for...in for arrays and strings is not a good practice, considering the order of enumeration is undefined. Here is a better implementation using iterators:
It works with any number of iterable arguments and they don't have to be the same length 😺