Skip to content

Instantly share code, notes, and snippets.

@phamleduy04
Last active April 23, 2024 04:36
Show Gist options
  • Save phamleduy04/581f2fc57bd670d3cc042c0b334205e5 to your computer and use it in GitHub Desktop.
Save phamleduy04/581f2fc57bd670d3cc042c0b334205e5 to your computer and use it in GitHub Desktop.
Transpose matrix js
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]
];
const transposeMatrix = (matrix) => {
const rows = matrix.length;
const cols = matrix[0].length;
const transposeMatrix = [];
for (let i = 0; i < cols; i++){
transposeMatrix[i] = [];
for (let j = 0; j < rows; j++) {
transposeMatrix[i][j] = matrix[j][i];
}
}
return transposeMatrix;
}
console.log(transposeMatrix(matrix));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment