Last active
November 20, 2018 20:22
-
-
Save tuvo1106/cd6ae2217a42049ddf9b390699264cde to your computer and use it in GitHub Desktop.
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
// An simple zip function with reduce() | |
const example = [[1,2,3], [4,5,6], [7,8,9]] | |
const zip = arr => { | |
//loop through outter array | |
return arr.reduce(function(outter, inner) { | |
// loop through inner arrays | |
inner.forEach(function(num, i) { | |
// check if there is an array to add zipped values to | |
if (outter[i] === undefined) { | |
// if not, will create a new one | |
let newArr = []; | |
newArr.push(num); | |
outter.push(newArr) | |
} else { | |
// if there exists an array, will add to it | |
outter[i].push(num) | |
} | |
}) | |
return outter | |
// set initial value of reduce to an empty array | |
}, []) | |
} | |
console.log(zip(example)) // [ [ 1, 4, 7 ], [ 2, 5, 8 ], [ 3, 6, 9 ] ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment