48
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

JavaScriptで二次元配列の行列を転置するワンライナー

日本語で検索してもコレというのが出てこなかったのですが、海外の記事に秀逸なワンライナーがあったのでご紹介。

元記事はコチラ。function()を使いたくなかったので代わりにアロー関数を使用しています。

コード

const transpose = a => a[0].map((_, c) => a.map(r => r[c]));

受け取った配列を回転します。

使用例

transpose.js
const transpose = a => a[0].map((_, c) => a.map(r => r[c]));

const array = [
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ]
];

transpose(array);
//    ↓
//[
//    [ 1, 4, 7 ],
//    [ 2, 5, 8 ],
//    [ 3, 6, 9 ]
//]

以上です。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
48
Help us understand the problem. What are the problem?