# How To Transpose A Matrix (2D Array) In JavaScript

By onjsdev

Nov 3rd, 2023

Transpose is a linear algebra concept used in different computer science fields such as image processing, graph theory and data analysis. It means swapping rows and columns of a matrix and its goal is to reorganize data into a more manageable format.

In this article, we will transpose a 2D array in javascript, which represents a matrix in linear algebra. We will implement this application with both the for loop and the javascript array `map()`

method

## Transpose A 2D Array In JavaScript With For Loop

In programming languages, 2D arrays represent a matrix and we simply iterate over 2D array using two loops and swap each rows and columns.

Here is how to transpose a matrix in javascript:

```
// Define a function named "transpose" that takes a matrix as an argument.
function transpose(matrix) {
// Create an empty array to store the transposed matrix.
const result = [];
// Loop through the length of the first row of the matrix.
for (let i = 0; i < matrix[0].length; i++) {
// Create an empty array to store the current column.
const arr = [];
// Loop through each row of the matrix.
for (let j = 0; j < matrix.length; j++) {
// Push the element at the current column and row to the array.
arr.push(matrix[j][i]);
}
// Push the completed column to the transposed matrix.
result.push(arr);
}
// Return the transposed matrix.
return result;
}
```

## Transpose A 2D Array In JavaScript With Array Methods

JavaScript has a wide range of array methods to manipulate an array instead of traditional for loops. In the following code snippet, we implemented the same example using one of the them, the map method

```
function transpose(matrix) {
const result = matrix[0].map((col, i) => matrix.map((row, j) => row[i]));
return result;
}
// Test case
const numbers = [
[1, 2, 3],
[4, 5, 6],
];
console.log(transpose(numbers));
/*
[ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
*/
```

## Conclusion

In this guide we've discussed how to transpose a matrix (2D array) with JavaScript using both for loops and array methods to obtain data in a more manageable form or to perform calculations in a more convenient manner.

Thank you for reading.