JavaScript - Generating combinations from n arrays with m elements

前端 未结 10 1574
一个人的身影
一个人的身影 2020-11-22 04:10

I\'m having trouble coming up with code to generate combinations from n number of arrays with m number of elements in them, in JavaScript. I\'ve seen similar questions about

10条回答
  •  囚心锁ツ
    2020-11-22 04:48

    You could take an iterative approach by building sub arrays.

    var parts = [[0, 1], [0, 1, 2, 3], [0, 1, 2]],
        result = parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
    
    console.log(result.map(a => a.join(', ')));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题