How would you implement the Cartesian product of multiple arrays in JavaScript?
As an example,
JavaScript
x
2
1
cartesian([1, 2], [10, 20], [100, 200, 300])
2
should return
JavaScript
1
9
1
[
2
[1, 10, 100],
3
[1, 10, 200],
4
[1, 10, 300],
5
[2, 10, 100],
6
[2, 10, 200]
7
8
]
9
Advertisement
Answer
Here is a functional solution to the problem (without any mutable variable!) using reduce
and flatten
, provided by underscore.js
:
JavaScript
1
12
12
1
function cartesianProductOf() {
2
return _.reduce(arguments, function(a, b) {
3
return _.flatten(_.map(a, function(x) {
4
return _.map(b, function(y) {
5
return x.concat([y]);
6
});
7
}), true);
8
}, [ [] ]);
9
}
10
11
// [[1,3,"a"],[1,3,"b"],[1,4,"a"],[1,4,"b"],[2,3,"a"],[2,3,"b"],[2,4,"a"],[2,4,"b"]]
12
console.log(cartesianProductOf([1, 2], [3, 4], ['a']));
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>
Remark: This solution was inspired by http://cwestblog.com/2011/05/02/cartesian-product-of-multiple-arrays/