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

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

Linda Hamilton
Release: 2024-12-15 12:42:12
Original
670 people have browsed it

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

Transposing a 2D-array with JavaScript's Condensed Syntax

Transposing a 2D array involves converting rows into columns and vice versa. While basic loop-based solutions exist, JavaScript offers a more concise approach that leverages functional programming techniques.

Consider the provided 2D array:

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

The concise transposition using map() can be expressed as:

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

Breaking down the code:

  1. array[0].map: Iterates over the first row of the original array.
  2. (_, colIndex): As the outer map iterates through empty elements, the underscore (_) placeholder is used instead of an actual value. colIndex represents the column index.
  3. array.map: For each column index, this inner map iterates through the original array.
  4. row => row[colIndex] : Extracts the element in the specified column for each row.

The result is a new 2D array where each row in the original array has become a column in the transposed array:

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

The above is the detailed content of How Can I Efficiently 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