一尘不染

JavaScript中多个数组的笛卡尔积

javascript

您将如何在JavaScript中实现多个数组的笛卡尔积?

举个例子,

cartesian([1, 2], [10, 20], [100, 200, 300])

应该回来

[
  [1, 10, 100],
  [1, 10, 200],
  [1, 10, 300],
  [2, 10, 100],
  [2, 10, 200]
  ...
]

阅读 295

收藏
2020-04-25

共1个答案

一尘不染

这是使用和提供的解决问题的功能解决方案(没有任何 可变变量 !),该提供者为:reduce``flatten``underscore.js

function cartesianProductOf() {

    return _.reduce(arguments, function(a, b) {

        return _.flatten(_.map(a, function(x) {

            return _.map(b, function(y) {

                return x.concat([y]);

            });

        }), true);

    }, [ [] ]);

}



// [[1,3,"a"],[1,3,"b"],[1,4,"a"],[1,4,"b"],[2,3,"a"],[2,3,"b"],[2,4,"a"],[2,4,"b"]]

console.log(cartesianProductOf([1, 2], [3, 4], ['a']));


<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>
2020-04-25