Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created May 16, 2020 21:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dfkaye/372779733dac8b33005c639b7dfe2446 to your computer and use it in GitHub Desktop.
merge 2 or more arrays into a matrix.
// 16 May 2020
// Killing time again.
// merge 2 or more arrays into a matrix.
//
// zip(a,b,c) returns
// [
// [a[0], b[0], c[0]],
// [a[1], b[1], c[1]],
// ... etc ...
// ];
function zip(arrays) {
arrays = [].slice.call(arguments);
var zipped = [];
var next;
var i = arrays.reduce(function(it, arr) {
return arr.length > it ? arr.length : it;
}, 0);
while (i--) {
next = [];
arrays.forEach(function(array) {
next.unshift(array[i]);
});
zipped.push(next);
}
return zipped;
}
/* test it out */
var a = "correct horse battery staple".split(' ');
var b = "123 456 789 0".split(' ');
var c = [ 1, true, 'way', ];
console.log( zip(a,b,c) );
/*
[
["correct", "123", 1],
["horse", "456", true],
["battery", "789", "way"],
["staple", "0", undefined]
]
*/
console.log(zip([], { length: 2 }));
/*
[
[undefined, undefined],
[undefined, undefined]
]
*/
console.log(zip("array-like-string", "" + Date.now()));
/*
[
["a", "1"]
["r", "5"]
["r", "8"]
["a", "9"]
["y", "6"]
["-", "6"]
["l", "2"]
["i", "3"]
["k", "2"]
["e", "7"]
["-", "7"]
["s", "9"]
["t", "5"]
["r", undefined]
["i", undefined]
["n", undefined]
["g", undefined]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment