Skip to content

Instantly share code, notes, and snippets.

@jonschlinkert
Last active February 8, 2024 08:26
Show Gist options
  • Save jonschlinkert/2c5e5cd8c3a561616e8572dd95ae15e3 to your computer and use it in GitHub Desktop.
Save jonschlinkert/2c5e5cd8c3a561616e8572dd95ae15e3 to your computer and use it in GitHub Desktop.
versatile JavaScript "zip" function. Works with objects, arrays, and yep - even strings.
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' ] ]
@kurellajunior
Copy link

kurellajunior commented Jan 5, 2022

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