Created
May 16, 2020 21:06
Star
You must be signed in to star a gist
merge 2 or more arrays into a matrix.
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
// 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