Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
38
Help us understand the problem. What is going on with this article?
@kznrluk

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

More than 3 years have passed since last update.

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

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

以上です。

38
Help us understand the problem. What is going on with this article?
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
kznrluk
JavaScriptが得意ですがPHPもできます。コメント、Twitterいつでもどうぞ。
ca21
CyberAgentの21年新卒エンジニアで作るQiita Organizationです

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
38
Help us understand the problem. What is going on with this article?