LoginSignup
88
53

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-01-13

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

元記事はコチラ。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 ]
//]

以上です。

88
53
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
88
53