Transposing a 2D Array in JavaScript with Map
Given a 2D array, transposing it means exchanging its rows and columns. For instance, transposing the following array:
[ [1,2,3], [1,2,3], [1,2,3], ]
would result in:
[ [1,1,1], [2,2,2], [3,3,3], ]
While it's possible to achieve transposition using loops, a more concise approach utilizes the map method:
output = array[0].map((_, colIndex) => array.map(row => row[colIndex]));
The map method iterates over the outer array (first array), creating a new array by calling the callback function for each element. In this case, the callback function creates an inner array by iterating over the inner arrays of the original array.
The callback function's parameters include:
During each iteration, the callback function retrieves the element at the specified column index from the inner array. By doing so for each inner array, it effectively constructs the transposed array.
The above is the detailed content of How Can I Transpose a 2D Array in JavaScript Using the Map Method?. For more information, please follow other related articles on the PHP Chinese website!