0

How to generate fully combinations of multiple arrays?

const source = [ ["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"] ]; const result = combination(source); 

Need result, like a cartesian product, but with combinations of all sizes:

["a"] ["a", "d"] ["a", "d", "g"] ... ["b"] ... ["b", "f", "i"] ... ["i"] 
1
  • 1
    what you have tried mate ? Commented Dec 15, 2018 at 3:51

1 Answer 1

1

How about this:

function cartesianProduct(arrArr) { if (arrArr.length === 0) return []; const [firstArr, ...restArrs] = arrArr; const partialProducts = cartesianProduct(restArrs || []); let ret = firstArr.map(elem => [elem]); ret = ret.concat(partialProducts); ret = ret.concat(partialProducts.reduce((acc, product) => { return acc.concat(firstArr.map(elem => [elem].concat(product))); }, [])); return ret; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, exactly what is needed!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.