JavaScript Transpose Matrix Rows to Columns

March 10th 2020

It’s fairly common that we have a matrix in JavaScript which is an array of arrays such as:

const matrix = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
];

In which we want to transpose the rows ie. the first row is matrix[0] and would evaluate to [1,2,3] into columns such that the first column of our returned matrix would evaluate to [1,4,7]. Let’s stub out our function to transpose the matrix:

const transpose = (matrix) => {
  //need to return a matrix transposed
}

// example input
const m = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
];

// expected output
// [
//   [1,4,7],
//   [2,5,8],
//   [3,6,9]
// ]

Since we are receiving and array (of arrays) and need to return an array we know we can start with JavaScript Map function as our initial step. But instead of mapping the original matrix array we want to reference all of the columns in the matrix so we can start to do this by mapping the first row: matrix[0]. Let’s look at what mapping through the first row of values looks like:

const transpose = (matrix) => {
  let [row] = matrix
  return row.map((value, column) => value)
}

// example input
const m = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
];

// expected output first row values
// [1,2,3]

We are also passing our column variable as the second argument as that is going to represent the column index that we’re mapping over: ie 0, 1, 2 in our example. Now we can make use of the original matrix array to go back and map through since we have our column identifier:

const transpose = (matrix) => {
  let [row] = matrix
  return row.map((value, column) => matrix.map(row => row[column]))
}

// example input
const m = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
];

// expected output
// [
//   [1,4,7],
//   [2,5,8],
//   [3,6,9]
// ]

Since we’re using matrix.map we will be mapping through the sub arrays (rows) of the matrix ie matrix[0], matrix[1], matrix[2] and we’re returning the row[column] so our first row would now look like [1,4,7] and moving forward the second and third arrays [2,5,8] and finally [3,6,9]. Now we have transposed our JavaScript matrix from rows to columns.