Transpose a matrix
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
`matrix` is an array of rows, all of the same length. Return the transposed matrix: the first column becomes the first row, the second column the second row, and so on. A matrix with no rows, or whose rows are empty, returns `[]`. Values are copied as they are, including `null` and `undefined`. Do not change the input.
What this exercise teaches
Reading matrix[0] for the width must come after the empty check, because matrix[0] is undefined when there are no rows. Mapping over matrix with the same index on both sides only works for square matrices.
A hint if you get stuck
The number of result rows is the length of the first input row. Build result row `j` by mapping over the input rows and taking `row[j]` from each.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Arrays and objects
- Group by a fieldFree
- Count by a fieldFree
- Remove duplicates by a fieldFree
- Split into chunksFree
- Zip two arraysFree
- Flatten one levelFree
- Pick some keysFree
- Sort by several keysFree
- Merge settingsFree
- Omit some keysFree
- Flatten to a depthFree
- Binary searchFree
- Two numbers that add upFree
- Values in both arraysFree
- Rotate an arrayFree