Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Transpose of a two-dimensional array - JavaScript
The transpose of a matrix (2-D array) is simply a flipped version of the original matrix. We can transpose a matrix by switching its rows with its columns.
For example, if we have a 3×3 matrix where the first row is [1, 1, 1], after transposing, the first column becomes [1, 1, 1].
Understanding Matrix Transpose
Let's visualize how transposition works with a simple example:
Original Matrix: [1, 1, 1] [2, 2, 2] [3, 3, 3] Transposed Matrix: [1, 2, 3] [1, 2, 3] [1, 2, 3]
Method 1: In-Place Transpose (Modifies Original)
This approach modifies the original array by swapping elements:
const arr = [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]
];
const transpose = arr => {
for (let i = 0; i
Original: [[1,1,1],[2,2,2],[3,3,3]]
Transposed: [[1,2,3],[1,2,3],[1,2,3]]
Method 2: Creating New Transposed Array
This approach creates a new array without modifying the original:
const arr = [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]
];
const transposeNew = matrix => {
return matrix[0].map((col, i) => matrix.map(row => row[i]));
};
const original = JSON.stringify(arr);
const transposed = transposeNew(arr);
console.log("Original:", original);
console.log("Transposed:", JSON.stringify(transposed));
console.log("Original unchanged:", JSON.stringify(arr));
Original: [[1,1,1],[2,2,2],[3,3,3]]
Transposed: [[1,2,3],[1,2,3],[1,2,3]]
Original unchanged: [[1,1,1],[2,2,2],[3,3,3]]
Method 3: Using Traditional For Loops
const arr = [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
];
const transposeTraditional = matrix => {
const rows = matrix.length;
const cols = matrix[0].length;
const result = [];
for (let i = 0; i
Original: [[1,4,7],[2,5,8],[3,6,9]]
Transposed: [[1,2,3],[4,5,6],[7,8,9]]
Comparison
| Method | Memory Usage | Modifies Original | Readability |
|---|---|---|---|
| In-place swap | Low | Yes | Medium |
| Array.map() | High | No | High |
| Traditional loops | High | No | Medium |
Conclusion
Use in-place transposition for memory efficiency when you don't need the original matrix. For preserving the original data, the map() method offers cleaner, more functional code.
Advertisements
