0
0

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 3 years have passed since last update.

配列の全組み合わせ

Posted at

いくつか記事を見かけますが・・・・forで回すのが多い。
ですが、簡単に

.reduce((zs, xs) => zs.flat().map(z => xs.map(x => [x, z].flat()))).flat()

これだけで全組み合わせができます

関数で

const combineArrays = (arrays) => arrays.reduce((zs, xs) => zs.flat().map(z => xs.map(x => [x, z].flat()))).flat()
> combineArrays([[1, 2], [3, 4]])
[ [ 3, 1 ], [ 4, 1 ], [ 3, 2 ], [ 4, 2 ] ]

> combineArrays([[1, 2], [3, 4], [5, 6]])
[
  [ 5, 3, 1 ],
  [ 6, 3, 1 ],
  [ 5, 4, 1 ],
  [ 6, 4, 1 ],
  [ 5, 3, 2 ],
  [ 6, 3, 2 ],
  [ 5, 4, 2 ],
  [ 6, 4, 2 ]
]

ぱっと出てこなかったので、自分のメモ書き程度に。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?