mirror of
https://github.com/Fechin/reference.git
synced 2026-11-29 16:40:48 +03:00
1.0 KiB
1.0 KiB
title, tags, layout
| title | tags | layout | |||||
|---|---|---|---|---|---|---|---|
| How to swap the rows and columns of a matrix in JavaScript |
|
note |
In this Article we will go through how to swap the rows and columns of a matrix only using single line of code in JavaScript.
This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.
Let's define this short function:
const transpose = matrix => matrix[0].map((col, i) => matrix.map(row => row[i]));
Or
const transpose = matrix => matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c]));
Or
const transpose = matrix => matrix.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), []);
Example
transpose([ // [
[1, 2, 3], // [1, 4, 7],
[4, 5, 6], // [2, 5, 8],
[7, 8, 9], // [3, 6, 9],
]); // ]