Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  121] [ 2]  / answers: 1 / hits: 80105  / 12 Years ago, thu, september 6, 2012, 12:00:00

How would you implement the Cartesian product of multiple arrays in JavaScript?



As an example,



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


should return



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

More From » arrays

 Answers
53

Here is a functional solution to the problem (without any mutable variable!) using reduce and flatten, provided by 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>





Remark: This solution was inspired by http://cwestblog.com/2011/05/02/cartesian-product-of-multiple-arrays/


[#83209] Wednesday, September 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
forrestn

Total Points: 552
Total Questions: 94
Total Answers: 101

Location: Sao Tome and Principe
Member since Thu, Apr 20, 2023
1 Year ago
;