what does the underscore perform?
The reason first argument to map()
is named _
is because its not used.
An underscore is usually picked by convention as a name for unused arguments.
but I don't understand why we're only acting on the first element of the array a[0]
Using a[0]
is arbitrary. Since all rows in a matrix have equal length, any index would work. We are doing this to obtain the number of columns.
Essentially, the first map()
iterates over the first row (all columns) and on each iteration, ignores the current column value and grabs the current column index. In other words, the first map()
iterates over the "width" of the matrix, from left to right, grabbing the current column index each time.
The second map()
is inside the first map()
. This means that it, for every column index, iterates over all the rows (height of the matrix) and on each iteration, creates a new row from the current row using the corresponding column index.
- Important thing to note is that
map
creates a new array each time so you are creating a new transposed matrix, not changing the initial one in any way.
Visual Example
If you start with the matrix:
[ ['a1', 'a2', 'a3'] ]
[ ['b1', 'b2', 'b3'] ]
Then on each step, here's what is happening (using M
for the original matrix and T
for the transposed matrix):
// Step1
columnIndex = 0
T[columnIndex][0] becomes M[0][columnIndex] which is "a1"
T[columnIndex][1] becomes M[1][columnIndex] which is "b1"
transposed row 0 becomes ["a1", "b1"]
// Step2
columnIndex = 1
T[columnIndex][0] becomes M[0][columnIndex] which is "a2"
T[columnIndex][1] becomes M[1][columnIndex] which is "b2"
transposed row 1 becomes ["a2", "b2"]
// Step3
columnIndex = 2
T[columnIndex][0] becomes M[0][columnIndex] which is "a3"
T[columnIndex][1] becomes M[1][columnIndex] which is "b3"
transposed row 2 becomes ["a3", "b3"]
And you end up with a transposed matrix:
[ ['a1', 'b1'] ]
[ ['a2', 'b2'] ]
[ ['a3', 'b3'] ]
Here's code with altered formatting and variable names to show more clearly what is happening. Open the console to see what is happening in each step.
var matrix = [];
matrix.push(['a1', 'a2', 'a3']); // first row
matrix.push(['b1', 'b2', 'b3']);
/*
matrix =
[ ['a1', 'a2', 'a3'] ]
[ ['b1', 'b2', 'b3'] ]
*/
function transpose(matrix) {
var firstRow = matrix[0];
var transposedMatrix = firstRow.map(function(UNUSED, columnIndex) {
console.debug('\ncolumnIndex = %d', columnIndex);
var transposedRow = matrix.map(function(row, idx) { // <-- idx is only used for logging, it's not necessary
console.debug('T[%d][%d] = becomes %o', columnIndex, idx, row[columnIndex]);
return row[columnIndex];
});
console.debug('transposed row %d becomes %o: ', columnIndex, transposedRow);
return transposedRow;
});
return transposedMatrix;
}
var transposed = transpose(matrix);
/*
transposed =
[ ['a1', 'b1'] ]
[ ['a2', 'b2'] ]
[ ['a3', 'b3'] ]
*/
console.dir(transposed);