Created
January 12, 2018 11:27
-
-
Save IAmAdamTaylor/97f4ffbcb9e4e9f060b9802b8d8e41a0 to your computer and use it in GitHub Desktop.
JavaScript - Transpose a 2D array
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
/** | |
* Transpose an array of arrays using matrix transposition. | |
* The array is returned, *NOT* transposed in place. | |
* | |
* Handles matrixes where the number of rows != number of columns. | |
* The number of columns in each row must be the same. | |
* E.g. | |
[ | [ | |
[1,2,3], | [1,2], | |
[4,5,6], | [3,4], | |
[7,8,9], | [5,6], | |
] | ] | |
becomes | becomes | |
[ | [ | |
[1,4,7], | [1,3,5], | |
[2,5,8], | [2,4,6], | |
[3,6,9], | ] | |
] | | |
* @param {Array} array The array to transpose. | |
* @return {Array} | |
*/ | |
function transpose( array ) { | |
let newArray = []; | |
for (let i = 0, len = array[0].length; i < len; i++) { | |
newArray.push( [] ); | |
for (let j = 0, len = array.length; j < len; j++) { | |
newArray[i].push( array[j][i] ); | |
} | |
} | |
return newArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment