Transpose A Matrix In JavaScript


By onjsdev

The transpose is a fundamental operation in linear algebra. It is used in field of image processing, graph theory and data analysis. Its purpose is to reorganize data into a more manageable form.

In this article, we will transpose a 2D array in javascript, which represents a matrix in linear algebra. We will implement this application with either for loops or also javascript array methods, map and reduce.

Transpose A 2D Array In JavaScript With For Loops

Transpose in linear algebra means swapping rows and columns of a matrix. The transpose of a matrix is usually represented by placing a small "T" on top of the original matrix, for example: A^T

Here is how to transpose a matrix in javascript using loops.

// 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 offers a wide range of array methods to manipulate an array so this application is also implemented 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;
}

After these implementations, you can call the functions with a 2D array parameter as in the following code snippet.

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 a linear algebra operation, transposing a matrix, which provides data in a more manageable form or to perform calculations in a more convenient manner with tradional loops and javascript array methods

Thank you for reading.