Skip to content

Instantly share code, notes, and snippets.

@IAmAdamTaylor
Created January 12, 2018 11:27
Show Gist options
  • Save IAmAdamTaylor/97f4ffbcb9e4e9f060b9802b8d8e41a0 to your computer and use it in GitHub Desktop.
Save IAmAdamTaylor/97f4ffbcb9e4e9f060b9802b8d8e41a0 to your computer and use it in GitHub Desktop.
JavaScript - Transpose a 2D array
/**
* 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