3
2

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.

TypeScript(JavaScript)でArrayのtranspose(転置・行列入れ替え)をする

Posted at

スクリーンショット 2019-05-31 17.39.09.png

の行列を入れ替えたい時ってありますよね。

const table = [
  ['www.apple.com', 'www.apple.com'],
  ['www.amazon.com', 'www.amazon.com', 'www.amazon.com'],
  ['www.google.com'],
].sort((a, b) => b.length - a.length);

table[0]
.map((_, idx) => table.map (row => row[idx]));

スクリーンショット 2019-05-31 17.26.46.png

undefinedが嫌な時もありますよね。

const table = [
  ['www.apple.com', 'www.apple.com'],
  ['www.amazon.com', 'www.amazon.com', 'www.amazon.com'],
  ['www.google.com'],
].sort((a, b) => b.length - a.length);

table[0]
.map((_, idx) => table.map (row => row[idx]))
.map(row => row.filter(v => v));

スクリーンショット 2019-05-31 17.32.52.png

まとめると

transpose = <T>(table: T[][]): T[][] => {
    return table
        .sort((a, b) => b.length - a.length)[0]
        .map((_, idx) => table.map(row => row[idx]))
        .map(row => row.filter(v => v));
}

via https://qiita.com/kznr_luk/items/790f1b154d1b6d4de398

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?