Transpose a matrix in JavaScript
Intermediate · 4 min read
A matrix is a grid of values, stored in JavaScript as an array of rows, where each row is an array too. Transposing it means turning the rows into columns: the first row becomes the first column, the second row the second column, and so on. Spreadsheets do this with "paste special, transpose". You need it when data arrives one row per person but you want one list per question.
In this tutorial you will write transpose, which turns [[1, 2, 3], [4, 5, 6]] into [[1, 4], [2, 5], [3, 6]]. You will also handle an empty grid and see what happens when the rows are not all the same length. You should know arrays and map.
Reading a grid
Each cell has two numbers: which row it is in, and which column. In JavaScript you read it with two sets of brackets, row first.
const grid = [[1, 2, 3], [4, 5, 6]];
console.log(grid[0][2]); // 3: row 0, column 2
console.log(grid[1][0]); // 4: row 1, column 0
This grid is 2 by 3: two rows, three columns. Its transpose is 3 by 2. The cell at row r, column c moves to row c, column r.
map and its index
map calls your function once per item and collects the results. Your function also receives the item's index as its second argument. When you only care about the index, name the first argument _.
console.log(['x', 'y', 'z'].map((_, i) => i)); // [ 0, 1, 2 ]
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
23 Transpose a matrix
fairTurn [[1, 2, 3], [4, 5, 6]] into [[1, 4], [2, 5], [3, 6]]. Handle an empty matrix, and say what happens to a ragged one.
Stuck? Three hints, smallest first
- 1. The result has one row per column of the input, so map over the first row to get the column indexes.
- 2.
rows[0].map((_, c) => rows.map((row) => row[c]))is the whole thing. - 3. An empty input has no
rows[0], so guard it before indexing.
Step 1: one column
Start small. How do you get column 0 out of the grid? Take cell 0 from every row.
const grid = [[1, 2, 3], [4, 5, 6]];
console.log(grid.map((row) => row[0])); // [ 1, 4 ]
console.log(grid.map((row) => row[1])); // [ 2, 5 ]
Column 0 is [1, 4]. That is exactly the first row we want in the answer.
Step 2: every column
Now do that for each column number. How many columns are there? As many as there are cells in the first row. So map over the first row, and use only its index c.
const transpose = (rows) => rows[0].map((_, c) => rows.map((row) => row[c]));
const grid = [[1, 2, 3], [4, 5, 6]];
console.log(transpose(grid)); // [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
The outer map runs three times, once per column. The inner map builds that column from every row. The values of the first row don't matter here, only how many there are, which is why the parameter is _.
Transposing twice gets you back where you started:
const transpose = (rows) => rows[0].map((_, c) => rows.map((row) => row[c]));
const grid = [[1, 2, 3], [4, 5, 6]];
console.log(transpose(transpose(grid))); // [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
Step 3: the empty grid
Try transpose([]) with the Step 2 code and it crashes:
const transpose = (rows) => rows[0].map((_, c) => rows.map((row) => row[c]));
try {
transpose([]);
} catch (e) {
console.log(e.constructor.name); // TypeError
}
An empty array has no rows[0], so rows[0] is undefined, and undefined has no map method. Check for an empty grid first and return an empty one:
const transpose = (rows) =>
rows.length === 0 ? [] : rows[0].map((_, c) => rows.map((row) => row[c]));
console.log(transpose([])); // []
console.log(transpose([[1, 2]])); // [ [ 1 ], [ 2 ] ]
The ? : is the conditional operator: if the test is true, use the first value, otherwise the second. A single row becomes a single column, as you would expect.
Step 4: rows of different lengths
A grid whose rows are not all the same length is called ragged. What happens to [[1, 2], [3]]?
const transpose = (rows) =>
rows.length === 0 ? [] : rows[0].map((_, c) => rows.map((row) => row[c]));
const ragged = transpose([[1, 2], [3]]);
console.log(ragged[1][1] === undefined); // true
console.log(JSON.stringify(ragged)); // [[1,3],[2,null]]
The second row has no column 1, so that cell reads as undefined. Notice the second line: JSON.stringify shows it as null, because JSON has no way to write undefined inside an array. If you compare results with JSON.stringify, a missing cell and a real null look the same.
The function doesn't refuse ragged grids. It fills the holes with undefined, and now you know that is what it does.
Step 5: the input is not changed
map always builds new arrays, so the original grid is safe:
const transpose = (rows) =>
rows.length === 0 ? [] : rows[0].map((_, c) => rows.map((row) => row[c]));
const grid = [[1, 2, 3], [4, 5, 6]];
transpose(grid);
console.log(grid); // [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
The full solution
The panel defines transpose and runs it on the grid, twice in a row, on a single row, on an empty grid and on a ragged one. Press Run and check the shape printed next to each result.
const transpose = (rows) =>
rows.length === 0 ? [] : rows[0].map((_, c) => rows.map((row) => row[c]));
const grid = [[1, 2, 3], [4, 5, 6]];
const ragged = transpose([[1, 2], [3]]);
console.log('input :', grid, `${grid.length}x${grid[0].length}`);
console.log('transposed :', transpose(grid), `${transpose(grid).length}x${transpose(grid)[0].length}`);
console.log('twice :', transpose(transpose(grid)), '<- back to the start');
console.log('one row :', transpose([[1, 2]]));
console.log('empty :', transpose([]));
console.log('ragged :', ragged, '<- the missing cell reads as undefined');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('rows become columns', transpose(grid), [[1, 4], [2, 5], [3, 6]]);
test('the shape flips', [transpose(grid).length, transpose(grid)[0].length], [3, 2]);
test('transposing twice restores the original', transpose(transpose(grid)), grid);
test('a single row becomes a single column', transpose([[1, 2]]), [[1], [2]]);
test('an empty matrix stays empty', transpose([]), []);
test('a ragged row leaves an undefined cell', ragged[1][1] === undefined, true);
test('which JSON would have shown as null, hiding it', JSON.stringify(ragged), '[[1,3],[2,null]]');
test('the input is not modified', grid, [[1, 2, 3], [4, 5, 6]]);
test('the cells are the same values, in new rows', transpose(grid)[0][1], 4);
The trick is to drive the outer map from rows[0], because the number of columns in the input is the number of rows in the output. The callback ignores the value and uses only the index, which is why the parameter is written _.
Two assertions cover the same ragged matrix on purpose. Reading the cell directly shows it is undefined; serialising the whole thing shows null. That is JSON.stringify having no way to represent undefined inside an array — worth knowing before you use it to compare results, here or anywhere.
Common mistakes
- Mapping over the rows instead of the first row.
rows.map(...)on the outside gives you as many results as there are rows, so the shape doesn't flip. - Forgetting the empty grid.
rows[0]isundefinedfor[], and the code throws aTypeError. - Trusting
JSON.stringifyto compare grids. It turnsundefinedcells intonull, hiding the difference.
Try it yourself
- Transpose a 3 by 3 grid of your own and check the corners stay in place while the other cells swap.
- Write
column(rows, c)that returns one column, using the idea from Step 1. - Make a version that throws an error if the rows are not all the same length.