Home > Web Front-end > JS Tutorial > How Can I Transpose a 2D Array in JavaScript Using the Map Method?

How Can I Transpose a 2D Array in JavaScript Using the Map Method?

DDD
Release: 2024-12-09 14:56:11
Original
491 people have browsed it

How Can I Transpose a 2D Array in JavaScript Using the Map Method?

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],
]
Copy after login

would result in:

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

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]));
Copy after login

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:

  • _: A placeholder variable that represents the current element but is not used.
  • colIndex: The index of the current column.
  • row: The current inner array.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template