Sitemap

FreeCodeCamp Daily Challenge Solution 5/9/2026

1 min readMay 16, 2026

--

Transposed Matrix (JavaScript)

Given a matrix (an array of arrays), return the transposed version of it.

To transpose the matrix, swap the rows and columns. E.g: a value at index [0, 1] should move to index [1, 0].

Get Riley Underwood’s stories in your inbox

Join Medium for free to get updates from this writer.

For example, given:

[
[1, 2, 3],
[4, 5, 6]
]

Return:

[
[1, 4],
[2, 5],
[3, 6]
]

My Solution (JS):

function transpose(matrix) {
console.log(matrix)
let transposedMatrix = []
// Given that each subarray in a matrix should always be the same length. repeat process for the length of the first subarray of the matrix.
for (let i = 0; i < matrix[0].length; i++) {
// Empty the row array every loop and add the nth element of the subarray for each iteration.
let row = []
// Each time the for loop repeats, the next element of each subarray in the forEach loop will be added.
matrix.forEach((subArr) => {
row.push(subArr[i])
})
transposedMatrix.push(row)
}

console.log(transposedMatrix)
return transposedMatrix;
}

If you have a different solution or an improvement to this one please feel free to comment with your ideas!

See all the solutions I’ve done for these practice problems: https://github.com/BoltenBeeper/FreeCodeCamp-Daily-Coding-Practice-Solutions

Note: I do not use LLMs or AI assistance to write my code. Feel free to use this solution to learn or improve.

Dave Cross also has a great solution on YouTube: https://www.youtube.com/@dave-cross

If you want to see more of me: boltenbeeper.github.io/portfolio

--

--

Riley Underwood
Riley Underwood

Written by Riley Underwood

0 followers

AKA BoltenBeeper - I build websites: boltenbeeper.github.io/portfolio