# mat.transpose()

{% hint style="success" %}
zip <mark style="color:yellow;">**array of rows**</mark> into <mark style="color:orange;">**array of columns**</mark>.&#x20;
{% endhint %}

{% tabs %}
{% tab title="👥 相關" %}
* [zip](../../../../iteration/generator/examples/zip "mention") is like the <mark style="color:purple;">**transpose**</mark> of a <mark style="color:yellow;">**matrix**</mark>.
{% endtab %}

{% tab title="💾 程式" %}
{% hint style="danger" %}
⭐️ 注意：原矩陣<mark style="color:yellow;">**各列**</mark>的<mark style="color:red;">**長度可以不一樣**</mark>，但經過 <mark style="color:blue;">**transpose()**</mark> 後「<mark style="color:yellow;">**各行**</mark>」(也就是新矩陣的各列)<mark style="color:yellow;">**長度都一樣**</mark>，只是<mark style="color:orange;">**可能有些元素**</mark>會是 <mark style="color:purple;">**undefined**</mark>❗️
{% endhint %}

* replit ⟩ [zip(arrays)](https://replit.com/@pegasusroe/JS-array-zip#zipArrays.mjs)

```javascript
/**
 * see the matrix in "columns".
 * @example
 * let m = [[1,2], [3], [5,6]];
 * m.transpose();    // [[1,3,5], [2,undefined,6]]
 * @return {[[*]]} array of "columns"
 */
const matrix_transpose = {
    /**
     * see the matrix in "columns".
     * - Note: may contain `undefined` elements if row lengths are different
     * @example
     * let m = [[1,2], [3], [5,6]];
     * m.transpose();    // [[1,3,5], [2,undefined,6]]
     * @return {[[*]]} array of "columns"
     */
    transpose() {
        return Array.from(
            { length: Math.max(...this.map(row => row.length)) }, // number of columns
            (_, j) => this.map(row => row[j])   // for each row, choose jth column
        )
    }
};

export default matrix_transpose;
```

💈範例：

```javascript
import matrix_transpose from '/.../matrix_transpose.mjs';
Object.assign(Array.prototype, matrix_transpose);

let m1 = [[1, 2], [3, 4], [5, 6]];
// 1 2
// ---                    1 | 2
// 3 4  --(transpose)-->  3 | 4  (see matrix in "columns")
// ---                    5 | 6
// 5 6

let m2 = [[1, 2], [3], [5, 6]];
m1.transpose() // [[1,3,5], [2,4,6]]
m2.transpose() // [[1,3,5], [2,undefined,6]]
```
{% endtab %}

{% tab title="⬇️ 應用" %}
* [mat.maxelementineachcolumn](mat.maxelementineachcolumn "mention")
{% endtab %}

{% tab title="📗 參考" %}
* [ ] QuickRef ⟩ [How to zip multiple arrays in JavaScript](https://quickref.me/zip-multiple-arrays)
* [ ] GitHub ⟩ [versatile JavaScript "zip" function](https://gist.github.com/jonschlinkert/2c5e5cd8c3a561616e8572dd95ae15e3)
{% endtab %}

{% tab title="📘 手冊" %}
* [array.from](../static-methods/array.from "mention")
{% endtab %}

{% tab title="🗣 討論" %}
* [How do I zip two arrays in JavaScript?](https://stackoverflow.com/a/22015930/5409815)
* [Transposing a 2D-array in JavaScript](https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript)
{% endtab %}
{% endtabs %}
