Transpose a two dimensional (2D) array in JavaScript
Last Updated :
25 Jan, 2025
Here are the different methods to transpose a two-dimensional (2d) array in JavaScript
1. Using array.map()
The map() method offers a cleaner and more functional approach to transposing.
JavaScript
let mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let trans = mat[0].map((_, colIndex) =>
mat.map(row => row[colIndex])
);
console.log(trans);
Output[ [ 1, 4, 7 ], [ 2, 5, 8 ], [ 3, 6, 9 ] ]
In this example
- mat[0].map() iterates over columns based on the first row's length.
- For each column index, mat.map() collects elements from each row.
2. Using the nested loop
A nested loop approach is a fundamental way to transpose a 2D array. It iterates through rows and columns, constructing the transposed array by flipping the indices.
JavaScript
let mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let trans = [];
for (let i = 0; i < mat[0].length; i++) {
let row = [];
for (let j = 0; j < mat.length; j++) {
row.push(mat[j][i]);
}
trans.push(row);
}
console.log(trans);
Output[ [ 1, 4, 7 ], [ 2, 5, 8 ], [ 3, 6, 9 ] ]
In this example
- Iterates over columns of the original matrix to create rows for the transposed matrix.
- Collects elements from each row for the current column and forms a new row.
- Adds each new row to the result array trans.
- The rows and columns of the original matrix are swapped.
3. Using reduce() Method
We can use reduce() method and map() for transposing the array.
JavaScript
let mat = [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
];
let mat2 = mat.reduce((prev, next) =>
next.map((item, i) =>
(prev[i] || []).concat(next[i])
), []);
console.log(mat2);
Output[ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]
In this example
- The reduce method iterates over each row, and for each column index, it concatenates the corresponding elements from each row to create a new transposed array.
- The result is a 2D array where rows and columns are swapped.
4. Using Zip and Unzip
Zip: Combining multiple arrays into a single array of paired elements. Each pair consists of elements at the same index from the original arrays.
JavaScript
let a1 = ['Alia', 'Riya', 'Charu'];
let a2 = [25, 30, 35];
let res = a1.map((name, index) =>
[name, a2[index]]);
console.log(res);
Output[ [ 'Alia', 25 ], [ 'Riya', 30 ], [ 'Charu', 35 ] ]
Combines elements from multiple arrays by pairing corresponding elements at the same index.
Unzip: Reversing the zipping process by splitting a paired array back into its individual components (arrays).
JavaScript
let a = [['Alia', 25], ['Bhavya', 30], ['Charu', 35]];
let res = a.reduce((acc, [name, age]) => {
acc[0].push(name);
acc[1].push(age);
return acc;
}, [[], []]);
console.log(res);
Output[ [ 'Alia', 'Bhavya', 'Charu' ], [ 25, 30, 35 ] ]
In this example
Extracts paired elements back into separate arrays based on their index in the pairs.