0

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']]
]
Jason
  • 3,379
  • 25
  • 32
  • Can you show us what have you achieved yet? – Rajesh Jan 19 '16 at 06:12
  • @Rajesh added above. – Jason Jan 19 '16 at 06:18
  • You could approach this by first flattening your array to: `[ [1, 0], [4], [5, 6], [29, 33] ]`, and then using your `cartesianProductOf` – Paul Jan 19 '16 at 06:36
  • That still produces the same value. – Jason Jan 19 '16 at 06:40
  • There is a language agnostic algorithm here: [*How can I compute a Cartesian product iteratively?*](http://stackoverflow.com/questions/2419370/how-can-i-compute-a-cartesian-product-iteratively). – RobG Jan 19 '16 at 06:43
  • Thank you. That doesn't address the recursive issue. – Jason Jan 19 '16 at 06:44
  • Is there any practical difference between `[ [ ['list', 'give', 'tell'], ['me',''] ],... ]` and `[ ['list', 'give', 'tell'], ['me',''],... ]`? – RobG Jan 19 '16 at 07:10
  • 1
    @JasonTFeatheringham—the answer I linked to gives an iterative solution, but you can make it recursive by passing the updated *indexes* array on each iterative call and concatenating the returns. If no indexes array is passed, assume it's the first call and create a zero filled indexes array. – RobG Jan 19 '16 at 07:31

0 Answers0