Given this sample data:
[
['a', 'b'],
['c', ['d', 'e' ] ]
]
I want to produce this result:
// the result order doesn't matter
[
['a', ['c', 'd']],
['a', ['c', 'e']],
['b', ['c', 'd']],
['b', ['c', 'e']],
]
Essentially, I understand this will deal with Cartesian Products, but the common reduction seems to only handle the first level, and I'm struggling with the recursion. The code I have come up with only handles shallow products.
function cartesianProductOf(a) {
return a.reduce( function(a, b) {
return flatten((a.map && a || [a]).map(function(x) {
if(Array.isArray(x)) console.log(x);
return (b.map && b || [b]).map(function(y) { return x.concat([y]); });
}), true);
}, [ [] ]);
};
cartesianProductOf([ ['a', 'b'], ['c', ['d', 'e' ] ] ]);
// results in
[
['a', 'c'],
['a', ['d', 'e']],
['b', 'c'],
['b', ['d', 'e']]
]