Perform Matrix Transpose in JavaScript

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Nested arrays

What you’ll learn

  • What the transpose AT means: turn rows into columns so (AT)ij = Aji.
  • How to implement it with a second buffer and nested loops in JavaScript.
  • A 2×3 reference example (output shape 3×2), a 3×3 square example, plus a live preview and Try it (target="_blank").

Overview

Transposing is one of the gentlest matrix operations: you copy each value from position (j, i) in the original into position (i, j) in the result. The grid “flips” so height and width swap.

Two programs

Rectangle 2×3 and square 3×3.

Live preview

Same numbers as the first program, computed in the browser.

Why a copy?

A separate array avoids stepping on values you still need while building the transpose.

Prerequisites

Nested loops and arrays of arrays (matrix[i][j]).

  • console.log and literals like [[1, 2, 3], [4, 5, 6]].
  • Knowing your rows and cols (or deriving them from matrix.length and matrix[0].length for proper rectangles).

What is the transpose?

The transpose of a matrix A is written AT. Its entries satisfy (AT)ij = Aji: row and column indices are swapped.

So if A has m rows and n columns, AT has n rows and m columns.

Shape m×n → n×m
Flip twice (AT)T = A

Formal rule

For all valid indices, (AT)ij = Aji. Implementation-wise you often write transposed[i][j] = matrix[j][i] when i ranges over columns of the original and j over rows, matching the loop bounds below.

Live preview

Built-in 2×3 sample from example 1. Press the button to see A and AT.

Matches the first JavaScript program’s numbers.

Live result
Press “Transpose sample”.

Algorithm

Goal: given matrix with rows × cols, fill transposed with shape cols × rows using transposed[i][j] = matrix[j][i].

Allocate output shape

The result has cols rows and rows columns when the input has rows × cols.

Copy with swapped indices

Nested loops: for each i in 0 .. cols-1 and j in 0 .. rows-1, assign transposed[i][j] = matrix[j][i].

Print

Print with outer loop over rows of the transposed matrix (length cols) and inner loop over columns (rows).

📜 Pseudocode

Pseudocode
function transpose(matrix, rows, cols, out):   // out is cols × rows
    for i from 0 to cols - 1:
        for j from 0 to rows - 1:
            out[i][j] ← matrix[j][i]
1

Transpose a 2×3 matrix (reference)

Classic layout: hold the original in a nested array, pass explicit rows and cols, build transposed with swapped dimensions. Also prints the original for context.

JavaScript
function transposeMatrix(matrix, rows, cols) {
  const transposed = [];
  let i, j;
  for (i = 0; i < cols; i++) {
    transposed[i] = [];
    for (j = 0; j < rows; j++) {
      transposed[i][j] = matrix[j][i];
    }
  }

  console.log("Original (" + rows + " x " + cols + "):");
  for (i = 0; i < rows; i++) {
    let line = "";
    for (j = 0; j < cols; j++) {
      line += matrix[i][j] + "\t";
    }
    console.log(line);
  }

  console.log("");
  console.log("Transposed Matrix (" + cols + " x " + rows + "):");
  for (i = 0; i < cols; i++) {
    let line = "";
    for (j = 0; j < rows; j++) {
      line += transposed[i][j] + "\t";
    }
    console.log(line);
  }
}

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
];
const rows = 2;
const cols = 3;

transposeMatrix(matrix, rows, cols);
Try it Yourself

Explanation

The assignment transposed[i][j] = matrix[j][i] is the whole idea. Loop ranges follow the swapped dimensions: i runs cols times, j runs rows times.

2

Transpose a 3×3 matrix

Square example: first row 1 2 3 becomes the first column of the result. Still uses a separate buffer (simplest and safest for learners).

JavaScript
const N = 3;

function transposeSquare(a) {
  const out = [];
  let i, j;
  for (i = 0; i < N; i++) {
    out[i] = [];
    for (j = 0; j < N; j++) {
      out[i][j] = a[j][i];
    }
  }
  return out;
}

function printMatrix(title, m) {
  console.log(title);
  let i, j;
  for (i = 0; i < N; i++) {
    let line = "";
    for (j = 0; j < N; j++) {
      line += m[i][j] + " ";
    }
    console.log(line);
  }
}

const a = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const t = transposeSquare(a);

printMatrix("A", a);
console.log("");
printMatrix("A^T", t);
Try it Yourself

Explanation

For square matrices, out is the same shape as a. In-place transpose (without extra memory) is possible for squares but easier to get wrong; two buffers keep the lesson clear.

Extensions

In place (square only). Swap a[i][j] with a[j][i] for i < j to avoid using a second matrix; watch indexing carefully.

Jagged vs rectangular. JavaScript arrays do not enforce uniform row length; validate every row before assuming matrix[0].length applies to all rows.

❓ FAQ

Take every row of the original matrix and write it as a column of a new matrix (or swap row index with column index at each entry).
It has 3 rows and 2 columns. In general an m×n matrix becomes n×m.
The entry at row i, column j of A^T equals the entry at row j, column i of A. In symbols: (A^T)_ij = A_ji (with your book’s index convention).
In general a non-square matrix changes shape, so you usually need a second buffer. For a square n×n matrix you can swap across the diagonal in place with care.
So each assignment transposed[i][j] = matrix[j][i] does not overwrite data you still need from the original matrix.
You touch every element once to fill the transpose: O(m·n) time for an m×n matrix, with O(m·n) space for the output array.

🔄 Input / output

To experiment, change the numbers inside matrix (and a in the square example) and adjust rows / cols so they stay consistent with how much of the structure you actually use.

Edge cases

Keep dimensions honest and guard against jagged rows.

Bounds

rows and cols

They must match the slice of the nested arrays you filled. Wrong counts produce wrong output or runtime errors when indexing.

Rows

Jagged arrays

If rows have different lengths, matrix[j][i] may be undefined. Prefer validating rectangular input first.

⏱️ Time and space complexity

TaskTimeExtra space
Transpose m × nO(m · n)O(m · n) for the output buffer

Summary

  • Rule: (AT)ij = Aji; sizes swap from m×n to n×m.
  • Code: copy into transposed[i][j] = matrix[j][i] with matching loop bounds.
  • Double transpose: (AT)T = A.
Did you know?

The transpose flips a matrix across its diagonal: rows become columns. If A is m × n, then AT is n × m, and (AT)T = A.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful