Transpose or swap the rows and columns of the given matrix – 2D array in JavaScript. Matrix swapping takes place diagonally.
🟢 Easy 🧩 Pattern – Arrays

Example
Original Matrix:
[
[ 1, 1, 1 ],
[ 2, 2, 2 ],
[ 3, 3, 3 ]
]
Transposed Matrix:
[
[ 1, 2, 3 ],
[ 1, 2, 3 ],
[ 1, 2, 3 ]
]Code language: JavaScript (javascript)JS code to transpose a square matrix
Since a square matrix has the same number of rows and columns, we only need to swap half of them. We exchange the values below the diagonal with values above the diagonal – think of it like swapping two triangles.
function transposeSquareMatrix(matrix) {
const length = matrix.length;
// Get the dimension of the square matrix,
// iterate through the lower triangle,
// swap elements below with elements above the diagonal
for (let i = 0; i < length; i++) {
// First loop to iterate through each row
for (let j = 0; j < i; j++) {
// Second loop to iterate each column until the diagonal
// And swap the elements
const temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
return matrix;
}
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
console.log(transposeSquareMatrix(matrix));
// [
// [1, 4, 7],
// [2, 5, 8],
// [3, 6, 9],
// ];Code language: JavaScript (javascript)JS code to transpose a rectangular matrix
function transpose(matrix) {
const output = [];
const rows = matrix.length;
const columns = matrix[0].length;
// We start with the columns first as we need to transpose
for (let j = 0; j < columns; j++) {
// Initialise a new row first
output[j] = [];
for (let i = 0; i < rows; i++) {
// Swap values row to column and column to row
output[j][i] = matrix[i][j];
}
}
return output;
}
const matrix = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
];
console.log(transpose(matrix));
// [
// [ 1, 2, 3 ],
// [ 1, 2, 3 ],
// [ 1, 2, 3 ],
// [ 1, 2, 3 ]
// ]Code language: JavaScript (javascript)