Home > Web Front-end > JS Tutorial > How Can I Easily Transpose a 2D Array in JavaScript?

How Can I Easily Transpose a 2D Array in JavaScript?

Patricia Arquette
Release: 2024-12-17 09:09:25
Original
413 people have browsed it

How Can I Easily Transpose a 2D Array in JavaScript?

Transposing a 2D Array with Ease in JavaScript

Transposing a 2D array involves converting rows into columns and vice versa. This is often done to reshape data for specific processing requirements. While using loops to achieve this is common, there's a more convenient approach.

Consider the following 2D array:

[
    [1,2,3],
    [1,2,3],
    [1,2,3],
]
Copy after login

To transpose it into:

[
    [1,1,1],
    [2,2,2],
    [3,3,3],
]
Copy after login

You can leverage the power of map:

output = array[0].map((_, colIndex) => array.map(row => row[colIndex]));
Copy after login

Understanding the map Function

map iterates over each element of an array, applying a callback function to transform the elements. The output is a new array containing the transformed values.

Breaking Down the Transpose Code

  • array[0] accesses the first row of the input array.
  • The callback function (_, colIndex) receives the element (_) and its column index (colIndex).
  • Inside the callback, array.map(row => row[colIndex]) iterates over each row, extracting the element at the specified column index.
  • The result is a new array of column values.

Conclusion

This concise approach using map streamlines the transposition process, eliminating the need for nested loops and simplifying the code considerably.

The above is the detailed content of How Can I Easily Transpose a 2D Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template