1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptで2次元配列のtranspose(行列入れ替え)

Posted at

やりたいこと

2次元配列のX軸Y軸を転置したい場合に、Pythonのnumpyで使える「transpose」関数と同じことをJavaScriptで行う場合のメモ。

以下はPythonの例。

import numpy as np

org = [[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]

np.array(org).transpose().tolist()
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

JavaScriptでやる方法

こちらの記事で紹介されているワンライナーで書く方法。ちょっとテクニカルな感じ。

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

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

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

Lodashが使える場合、zip関数を使うと簡単。

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

_.zip.apply(null, org)
// [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

おしまい。

1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?